Unity3D – Access GameObjects and Components – CSharp

In Unity3D GameObjects are all entities in Unity scenes.

MAIN TOP MENU> GameObject>
– Particle System
– Camera
– GUI Text
– GUI Texture
– 3D Text
– Directional Light
– Point Light
– Spot Light
– Area Light
– Meshes
– etc…

To manage GameObjects in code you have to use the ‘gameObject’ base class.

In Unity3D Components are all ‘modifiers’ you can attach to a Gameobject.

MAIN TOP MENU> Components>
– Mesh
– Effects
– Physics
– Physics 2D
– Navigation
– etc…

Accessing this GameObject

1. Create a Cube, go to Inspector and add the script ‘DestroyBasic.cs’ as component.

DestroyBasic.cs:


using UnityEngine;
using System.Collections;

public class DestroyBasic : MonoBehaviour
{
    void Update ()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            Destroy(gameObject); // notice the keyword gameObject
        }
    }
}

Play, press Space to destroy it.

Notice: ‘Destroy(gameObject)’, you can use simple the keyword ‘gameObject’ and Unity3D will destroy the game object attached to the script.

Accessing this Component

1. Create a Cube, go to Inspector and add the scripts:
– ‘OtherScript.cs’ as component
– ‘example.cs’ as component

example.cs:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        // first declare the variable otherScript of type OtherScrip and store the component 'GetComponent'
        // type variablename = get <scriptname>
        OtherScript otherScript = GetComponent<OtherScript>();
        otherScript.DoSomething(); // manipulate the component
    }
}

Accessing Other GameObjects – Inspector assignable references

If you set a varible as ‘public’ you can assign it in Inspector, even while you are playing!


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // scope type variablename
    public Transform target; // Setup in Inspector
    void Update() {
        target.Translate(0, 1, 0);
    }
}

Below you can drag a Gameobject that contains the ‘OtherScript’ on the target slot in the inspector.


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // scope type variablename
    public OtherScript target; // Drag and Drop in Inspector a Gameobject with the script 'OtherScript' 
    void Update() {
        target.foo = 2;              // using OtherScript variables
        target.DoSomething("Hello"); // usibg OtherScript functions
    }
}

Located through the object hierarchy

1. Create the hierarchy:

Forearm (parent)
– Hand (child)

Attach to Forearm example.cs:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        transform.Find("Hand").Translate(0, 1, 0); // find childs with name
    }
}

Once you have found the transform in the hierarchy, you can use GetComponent to get to other scripts.


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        transform.Find("Hand").GetComponent<OtherScript>().foo = 2;
        transform.Find("Hand").GetComponent<OtherScript>().DoSomething("Hello");
        transform.Find("Hand").rigidbody.AddForce(0, 10, 0);
    }
}

You can loop over all children:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        foreach (Transform child in transform) {
            child.Translate(0, 10, 0);
        }
    }
}

Located by name


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Start() {
        // type varname = find the gameobject SomeGuy
        GameObject go = GameObject.Find("SomeGuy"); // find in Project window the object with name 'SomeGuy'
        // manipulate SomeGuy 
        go.transform.Translate(0, 1, 0);

        GameObject player = GameObject.FindWithTag("Player");
        player.transform.Translate(0, 1, 0);
    }
}

Located by tag

To assign a tag go to Inspector> Tag> Add Tag


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Start() {
        // type varname = find a gameobject with tag Player
        GameObject player = GameObject.FindWithTag("Player");
        // get from Player the component OtherScript
        player.GetComponent<OtherScript>().DoSomething();
    }
}

Passed as parameters


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // se il trigger entra in contatto con altri oggetti
    void OnTriggerStay(Collider other) {
        // se gli altri oggetti hanno un rigidbody
        if (other.rigidbody)
            // aggiungi una forza
            other.rigidbody.AddForce(0, 2, 0);
        
    }
}


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // se il trigger entra in contatto con altri oggetti
    void OnTriggerStay(Collider other) {
        // se gli altri componenti hanno lo script OtherScript
        if (other.GetComponent<OtherScript>())
            // ottieni OtherScript e fai qualcosa
            other.GetComponent<OtherScript>().DoSomething();
        
    }
}

All scripts of one Type

Find any object of one class or script name.

FindObjectOfType


// Search object of class GUITexture

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Start() {
        GUITexture texture = FindObjectOfType(typeof(GUITexture));
        if (texture)
            Debug.Log("GUITexture object found: " + texture.name);
        else
            Debug.Log("No GUITexture object could be found");
    }
}  

FindObjectsOfType

Il precedente era singolare ‘FindObjectOfType’, questo è plurale ‘FindObjectsOfType’


// When clicking on the object, it will disable all springs on all 
// hinges in the scene

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void OnMouseDown() {
        HingeJoint[] hinges = FindObjectsOfType(typeof(HingeJoint)) as HingeJoint[];
        foreach (HingeJoint hinge in hinges) {
            hinge.useSpring = false;
        }
    }
}

My website: http://www.lucedigitale.com

Ref: http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html