Changing gameobject assigned to a variable on input.getkey.


Right, I'm using the flocking script, which has a variable called chasee. The value of this variable is assigned to a GameObject, which is selected in the inspector.

What I want to do is, using an If statement, change the gameobject that is associated with this variable on a keypress

I'm fine with structuring everything but how I would phrase changing the chasee variable.

Its in javascript btw.

You'll have to get a reference to the game object you want to change it to. There are many different ways to do this. You could either have two variables you set in the inspector or use any of the different Find() methods.

Using two inspector variables could look like this:

var chasee :GameObject;
var otherTarget :GameObject;

function Update() {
    // Cycle between targets
    if (Input.GetKey(KeyCode.Return)) {
        var oldTarget = chasee;
        chasee = otherTarget;
        otherTarget = oldTarget;

I did a quick forum search for the flocking script and came up with this link... (3rd post from top)

Chasee is a private variable in the script. So I am guessing you've modified it to public in order to access it via the inspector.

Anyways assuming the flocking script is a child of some gameobject, here's how i would go about finding the gameobject, and setting the chasee parameter on its flocking script child object...

    GameObject myGameObject;

    GameObject objectWithFlockingScript = GameObject.FindGameObjectWithTag("someTag");

    var other : FlockingScript = gameObject.GetComponent(FlockingScript);        

    if (Input.GetKey("w"))
        scriptToAccess.casee = myGameObject;