#I just took a look over Google and I
1 messages · Page 1 of 1 (latest)
Thread
In this video we see how to call a function that is defined in another script, to do this we need to solve two different problems, the first one is how to access a function that is defined in another script, for that we need to work with an object of the type corresponding to the script in which the function we want to call is defined.
To fully ...
I did this guide but it seems so unnecessarily complicated
so I have to make a new tag each time I want to do this?
Oh definitely not. Just to be sure, are you trying to reference different GameObjects, or have different scripts on a same object see each other?
Basicly I want variables to work on both scripts
and functions
And they arent on the same object but on 2 different ones
If you have a moment, we can create two basic scripts on a same GameObject, see them work, and then extend the idea to disparate objects. It shouldn't take long.
Consider the following two MonoBehaviours:
{
B _b;
void Start() {
_b = GetComponent<B>();
}
public void SomeMethod()
{
Debug.Log("I am a method on A");
}
}```
```public class B : MonoBehaviour
{
A _a;
void Start()
{
_a = GetComponent<A>();
_a.SomeMethod();
}
}```cs
If you put those on the same GameObject, B will contain a reference to A and A will contain a reference to B.
I just made an edit, but you should see B add a message in the console, executed from a method on A. Does this make sense?
B can see the method in A because of the public keyword before the method.
Let me know if any of this doesn't seem clear. If you try it in editor, you should be able to see how it works. @pastel zodiac
Okay. I can talk a bit more about why this works, but this is a good place to start.
so what exactly is A _a;?
Okay, so _a is the name I gave to a variable that points to the class called A.
ohh so thats a class
why do we not have to specify that its a class?
Like
public class A _a;
or something
Well, it's implied. A is the data type, kind of like float, string etc. When you define a class, you can think of it as setting up a new type of data.
class is actually a keyword that demarks when a new class definition is about to begin.
A _a; in this case is creating a variable to hold the class reference. I put an underscore ahead of it because I made it private - it's a common convention.
But, creating the variable doesn't actually fill it with anything. In the Awake method, I give it a value GetComponent<A>(), which fetches the MonoBehaviour of that type on the same object and stores it.
Awake() is similar to Start(), but executes earlier, if you weren't sure.
I edited the above scripts to use Start(), in case that looks more familiar.
Thank you for all the help