Hello.
I’m completely new to Unity and thus need some help because I have a problem I cannot solve the way I’d usually do.
Before I start working on the project I have in mind, I need to get some experience with Unity so I do smaller stuff (at the moment I do pong) to get used with Unity. So far I have to say that Unity has a unique, very comfortable workflow, but there’s one thing I cannot do the way I wanted to.
The problem I have is that I need to manipulate/access properties of different GameObjects.
Usually I would write a game or a logic-Object, create a new instance and call some sort of start()-Method from withing the main-Method. This logic-method would then manage everything (or most of the stuff) and if I needed to access a variable from another part of the script, I could just use base.getBLAH().
The problem is that in Unity, when you attach a script to a GameObject, it’s isolated since there is no main-Method.
I worked around the problem by turning the variables I need into public class variables. While this is the most convenient and performance-efficient way, it also has a major drawback. The variable shared across all instances and thus totally useless when I create anything more complex than pong.
So far I’ve read about SendMessage() and GetComponent(), but I don’t quite understand how to use them yet. I would appreciate it if someone would help me at one part of my code.
Here’s my specific problem:
I’m writing pong and have a “Ball” component. I need to access the position of the Ball from within the “Player” GameObject (and other places too, but this one should do for me to understand).
Ball.cs:
public class Ball : MonoBehaviour {
[...]
public static Vector3 pos;
[...]
// Update is called once per frame
void Update () {
[...]
pos = mytransform.position;
}
Player.cs
public class Player : MonoBehaviour {
[...]
void OnCollisionEnter(Collision collision)
{
if(mytransform.position.z > Ball.pos.z) {
[...]
}
[...]
}
}
You should get the idea.
I also need to access other stuff from within different classes, but I think that if someone shows/explains me how to solve this problem here, I’ll be able to do the rest.
Thanks in advance.