DrakeTruber
DrakeTruber

Reputation: 327

Manipulating X and Y Properties Unity2D-Javascript

I'm new to Unity and Javascript, both of which I'm using for my new project, and my question is this: why must it be so difficult to simply access and manipulate x and y values? My whole life I've used AS for Flash and recall better days, when one could simply

trace(mc.x);

and

mc.x++;

But from the research I've done it seems that one can't even access a Game Object without typing out a tedious

GameObject.Find("mc")

And that's just for accessing the Object! As far as finding the object's position or for even moving an object to a point, I have no idea. I tried finding the answer online, but couldn't find anything.

And yes I understand that one can add to an object's position through

GameObject.Find("mc").transform.Translate(1,0,0);

But even that seems clumsy compared to the AS equivalent of a simple

mc.x++;

Thank you for your time.

Upvotes: 0

Views: 43

Answers (1)

Gabriel Sibley
Gabriel Sibley

Reputation: 378

It sounds like maybe you need to learn more about components. Any public GameObject field in your script classes (as long as they extend Component, or even better MonoBehaviour) can be filled with a reference to another GameObject by dragging and dropping the object in the Inspector pane. You can then reference the variable like normal.

GameObjects by themselves are not particularly useful, but you can use GetComponent() to find parts you need on those objects -- like Transform, Renderer, Rigidbody, or your own Component classes. You can also create public fields that have the specific Component sub-type you need, and reference them directly.

For example:

var anObject : GameObject;
var aTransform : Transform;
function Start(){
    if(anObject != null)
        Debug.Log("I know about an object called " + anObject.name);
    if(aTransform != null)
        Debug.Log("I know about a transform at " + aTransform.position);
}

As a side note - GameObject.Find() is really slow! If you use it too much your game will not perform well.

Upvotes: 2

Related Questions