how to pass values through action

I’ve saw many times:

  • Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

and now when I wanted to simplify things to make an action instead of constantly calling get component, … and just pass the ref to action and later use it, … I came in to a wall, …

	Action Func;
	void Test(){
		Func = Test1;
//		Func(/*I thought I declare it what to pass in here*/); // even without this line I get 2 errors
	}
	void Test1(bool bol){
		
	}

and this 2 errors are that I get:

error CS0123: A method or delegate `GUI3DCursor.Test1(bool)' parameters do not match delegate `System.Action()' parameters
error CS0428: Cannot convert method group `Test1' to non-delegate type `System.Action'. Consider using parentheses to invoke the method

BUT if I remove bool I get none errors

void Test1(){

so what should I do to make it able to accept anything for an action?

1 Answer

1

You want an Action< Type >:

void Hello(int num)
{
    Debug.Log("Hello " + num);
}

void Run()
{
    Action<int> hi = Hello;
    hi.Invoke(5);
}

thank you soo much I was trying with (), ... in action and after action and nothing worked :) didn't know I have to use <>

Note that a delegate is slower than a reference. I would continue with the GetComponent if not for the sake of knowledge. Also, just for info, the Invoke is not necessary, the compiler will add it anyway so you can use: hi(5);

well @fafase you know I know how to use GetComponent().Stuff, ... IT's actually 1 of my first Type asked questions with some thumbs downs, ... but actually right now I gained knowledge about 2 things: 1. How to use Action and pass values 2. That action is actually slower process than actually just referencing, ... I didn't even thought possible the 2. one, ... BUT for sake of knowledge I should use Action more as atm I'm experimenting and learning inside this waters, ....