Ethan
Ethan

Reputation: 21

Reading variables from other objects in Unity

Long story short. I need to get the Vector3 value of a number of objects and put all of them in an array. For each Game Objects I need to run the following code:

public class Pos : MonoBehaviour {

    public Vector3 pos;

    // Update is called once per frame
    void Update()
    {
        pos = transform.position;
    }
}

And the code that stores all the values in an array is the this other one:

public class GetPos : MonoBehaviour {

    public Vector3[] Pos = new Vector3[41];

    //get all the space objects
    GameObject Go = GameObject.Find("Go");
    GameObject Mediterranean = GameObject.Find("Mediterranean");

    private void Start()
    {
        //be able to call all the game objects
        Pos GoPos = Go.GetComponent<Pos>();
        Pos MedPos = Mediterranean.GetComponent<Pos>();

    //make pos contain all possible positions.
        Pos[0] = GoPos.pos;
        Pos[1] = MedPos.pos;
    }
}

I'm not sure why, but whenever I run the code, all of the values of the array Pos are equal 0. What am I doing wrong and how do I fix it?

P.S. There are more objects which need values than what I mentioned(41 in total), but once I get one, it's basically a copy paste job.

Upvotes: 1

Views: 100

Answers (1)

Ignacio Alorre
Ignacio Alorre

Reputation: 7605

Let's start with this. Avoid updating a variable in UpDate(), this will cause to refresh this variables once per frame which means several times per second. Which is not not very efficient.

Besides, as I understand from your code, you will read this variable pos, just once in the GetPos, during the start().

Since you are trying to store this possition form the transform.position, I assume you have this class attached to a GameObject.

In case that is the situation, a set of GameObjects of two different types: Go and Mediterranean, you can get their possitions like this:

GameObject.FindGameObjectWithTag("go").transform.position;

or

GameObject.FindGameObjectWithTag("mediterranean").transform.position;

And you will not need to store this position in any variable of your class, since the gameobject itself contents a transform element with the position.

You can read more about tagging GameObjects here

And about your specific problem, that you get a 0 value, this may be because you need to access each of the components of the vector3 independently

Pos[0] = new Vector3(GoPos.pos.x,GoPos.pos.y,GoPos.pos.z);

I can not test it right now, but it should be something similar to that

You can read more about vector3 here

Upvotes: 2

Related Questions