Skip to content

Instantly share code, notes, and snippets.

@nasser
Created November 15, 2013 20:12
Show Gist options
  • Save nasser/7490835 to your computer and use it in GitHub Desktop.
Save nasser/7490835 to your computer and use it in GitHub Desktop.
// Talking to objects
// 1. Find the object
// 1.a Manually dragging in the editor (public variables only)
// 1.b GameObject.Find
// 1.c GameObject.FindWithTag
// 1.d GameObject.FindGameObjectsWithTag
//
// 2. Find the component
// 2.a Builtin (.transform)
// 2.b Custom (GetComponent<ComponentName>())
//
// 3. Call functions or set variables
// 3.a Call functions directly (if using GetComponent<>())
// 3.b Set variables directly (if using GetComponent<>())
// 3.c SendMessage/BroadcastMessage (if not using GetComponent<>())
using UnityEngine;
using System.Collections;
public class CubeClicker : MonoBehaviour {
public GameObject otherObject;
public GameObject scoreObject;
void Start() {
// alternatives to manual dragging
scoreObject = GameObject.Find("Score"); // 1.b
otherObject = GameObject.FindWithTag("SphereTag"); // 1.c
}
void OnMouseDown() {
Debug.Log("You clicked the cube!");
// builtin components
// object .component.function/parameter
otherObject.transform.Rotate(0, 0, 100); // 2.a
// custom components, calling function
// object . component . function/parameter
otherObject.GetComponent<SphereLogic>().DoubleInSize(); // 2.b, 3.a
// any component on otherObject with DoubleInSize function, run it
otherObject.SendMessage("DoubleInSize"); // 3.c
// any component on otherObject with TripleInSize function, run it, dont complain
otherObject.SendMessage("TripleInSize", SendMessageOptions.DontRequireReceiver); // 3.c
// custom components, setting variables
// object . component . function/parameter
scoreObject.GetComponent<ScoreScript>().score += 100; // 2.b, 3.b
GameObject[] allTheSpheres = GameObject.FindGameObjectsWithTag("SphereTag"); // 1.d
for(int i=0; i<allTheSpheres.Length; i++) {
// object . function/parameter
allTheSpheres[i].SendMessage("DoubleInSize"); // 3.c
// object . component . function/parameter
allTheSpheres[i].GetComponent<SphereLogic>().DoubleInSize(); // 2.b, 3.a
}
}
}
using UnityEngine;
using System.Collections;
public class ScoreScript : MonoBehaviour {
public int score;
}
using UnityEngine;
using System.Collections;
public class SphereLogic : MonoBehaviour {
public void DoubleInSize(float amount) {
// transform.localScale = new Vector3(8, 8, 8);
transform.localScale *= amount;
}
public void TripleInSize() {
transform.localScale *= 1.5f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment