This tutorial explains how you can write a script in C# that can access other objects and then modify their components. In this example, we will attach a script to the Main Camera and then use that script to access a Cube object and modify it’s position, rotation and scale.
Here is the sample code that is attached to the Main Camera and accessing the Cube object.
using UnityEngine; using System.Collections; public class moveOtherObject : MonoBehaviour { // this script accesses another object and modifies its components // it can be attached to any other object e.g script and is accessing a Cube // this is the other game object you want to access public GameObject target; // Use this for initialization void Start () { target = GameObject.Find ("Cube"); } // Update is called once per frame void Update () { target.transform.Translate (0f, 0f, 0.1f); target.transform.Rotate (0f, 0f, 1f); target.transform.localScale = new Vector3 (1.5f, 1.5f, 1.5f); } } |