#I just took a look over Google and I

1 messages · Page 1 of 1 (latest)

pastel zodiac
#

Thread

#

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?

modest robin
#

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?

pastel zodiac
#

and functions

#

And they arent on the same object but on 2 different ones

modest robin
#

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

pastel zodiac
#

sorry im back

#

Ill try it out rn

#

thanks!

modest robin
#

Okay. I can talk a bit more about why this works, but this is a good place to start.

pastel zodiac
#

so what exactly is A _a;?

modest robin
#

Okay, so _a is the name I gave to a variable that points to the class called A.

pastel zodiac
#

ohh so thats a class

#

why do we not have to specify that its a class?

#

Like

#

public class A _a;

#

or something

modest robin
#

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.

pastel zodiac