#OnClick.AddListener not working.
1 messages · Page 1 of 1 (latest)
Please cache the result of GetComponent - calling it multiple times and fetching the same thing is horrendously bad practice
And also:
Don't use Find methods!
Find methods in Unity are an often-tempting solution to referencing a scene object. However, there is always a better solution.
Whenever you call a Find method, Unity must traverse your entire scene hierarchy and check every single object until it finds a match; and the methods which return arrays will always traverse the entire hierarchy regardless.
This is inefficient! It means that the more objects you add to your scene, the slower these methods become; and it gets even worse if you are calling them multiple times.
A non-exhaustive list of Find methods to avoid:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
To read about a better solution, type []getareference or []getref
[]getref
How to get a reference
"How do I access a variable from another script?" is usually one of the first questions we ask when learning Unity. Whether you are C# beginner or a C# professional, understanding the way Unity does things differently can be confusing.
🌳 If the objects are already present in the scene hierarchy...
... then you can use the SerializeField attribute on a field, and assign it by dragging the object which has the script you want to access onto the field slot. This also works if the two scripts are on the same object.
[SerializeField] private SomeScript someScript;
If the objects are instantiated prefabs...
... then you can use a form of injection after you call Instantiate:
SomeScript.cs
public GameManager TheManager { get; set; }
GameManager.cs
var clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().TheManager = this;
i changed it and i will change GameObject.Find later. But do u know why my buttons are not working?
Well, what do you mean by "not working"? Do you get an error? Does the method call but something inside it fails? Does the method not call?
You need to give way more info than just "not working"
Im not getting anything i click it and nothing happens. Function works i checked it.
You've checked? Like with Debug.Log (or a breakpoint)
i called it on start and it worked.
Okay but that doesn't mean it's being called when the event is fired
okay when im debugging event is working
but still when i put the function it's not working.
