How do I shorten a gameObject.GetComponent
spawned.GetComponent<Button>().onClick.AddListener(delegate { gameObject.GetComponent<controller>().UpdateFeed("whatever"); });
This code here puts a listener on my button and interacts with another script, but I, for the life of me, cannot figure out how to shorten the "gameObject.GetComponent()" part as to not waste space when adding listeners to other buttons. How do I shorten it?
Is the delegate code always the same or is it always different?
It is often different, as I set a different function for each button that I instantiate.
The last example lets you retain custom control over the delegate code and encapsulates all the other guff into a couple of methods.
But as I said unless you intend to be writing this a lot I wouldnt bother. Its not a long line of code.
Answer by sacredgeometry · Aug 13, 2019 at 12:40 PM
Methods that return a value can just be treated like that value in situ.
So
int myInt = 0;
And
int GetMyInt()
{
return 0;
}
Are equivalent in use
i.e
myInt.ToString();
// and
GetMyInt().ToString();
Both evaluate to the same outcome i.e. a string with a value of "0"
With that in mind you can store the output of methods into variables..
So you can do:
var myComponent = gameObject.getComponent();
And then you can just reference the object by using the variable.
Does that make sense?
If you are going to store it somewhere you need to store it in a context/scope which doesnt deallocate it. So on the instance of a component would be a good place. If you declare it inline you will lose it as soon as the you finish executing that method.
Your answer
Follow this Question
Related Questions
Value doesn't change in game when updated. 2 Answers
How to add gameobjects to a grid? 0 Answers
How do I get the type of a Monobehaviour? 2 Answers
Input Command Issues 0 Answers