Hey everyone.
I’m fairly new to both Unity and programming. Recently I finished my first project, which was based on a course. In the last few days I’ve been trying to understand how things work, by doing some changes on the code and adding some features the course didn’t cover.
So, I’m having a hard time trying to figure out how to call methods that are from another script. I did some research and I made it work in some cases, although not really having a full understanding why it really works.
Say we have ScriptA and ScriptB, and in ScriptA I wanna call a Method from ScriptB.
public class ScriptB
{
public void DoSomething()
{
Debug.Log("Method from script B was called");
}
}
After some extensive research and a lot of tests I ended up with 3 different solutions.
Solution 1:
Attach both scripts to the same object, lets call it ObjectA. In this case, ScriptA will look like this:
public class ScriptA;
{
private ScriptB scriptB;
void Start()
{
scriptB = GetComponent<ScriptB>;
}
void Update()
{
scriptB.DoSomething();
}
}
Here I got a little confused. Why I have to “GetComponent”? I mean, isn’t the variable scriptB a type from the class ScriptB? Why I can’t just invoke the method without this line of code? Ok, moving on.
Solution 2:
Attach the ScriptA to ObjectA, and ScriptB to ObjectB. Here, i have to make the field scriptB public, so in the inspector I can put ObjectB inside this field.
public class ScriptA;
{
public ScriptB scriptB;
void Update()
{
scriptB.DoSomething();
}
}
In this case, I can invoke the method in a direct way.
Solution 3:
Solution 3 is using a Tag on ObjectB (lets call the tag just “B”), then we find the ObjectB in the script A.
public class ScriptA;
{
private ScriptB scriptB;
void Start()
{
scriptB = GameObject.FindGameObjectWithTag("B").GetComponent<ScriptB>;
}
void Update()
{
scriptB.DoSomething();
}
}
And if there’s some other approach that I missed, I would be glad to know about.
Since I’m very tired (6 AM here), theres a pretty good chance I made some mistakes when typing the code. Also, my English is pretty bad, but I tried my best. Feel free to ask me anything.
Really appreciate any help!