- Home /
How getting transform of another GameObject C#?
I want that, if a sphere collide with a plane, a cube start to fall.
This is the plane script but doesn't work:
public float speed = 1;
void OnTriggerEnter(Collider other){
if(other.gameObject.name == "Sphere"){
move the cube with transform.translate
}
}
I know that i have to use GetComponent but I don't know how.
Plese, someone help me ^^
Well you won't be able to access it unless you have one:
public Transform cube;
...
cube.Translate(...);
I did this, put the cube in the inspector but desn't work.
using UnityEngine; using System.Collections;
public class PlaneScript : $$anonymous$$onoBehaviour {
public Transform myCube; public float speed = 1;
void OnTriggerEnter(Collider other){ if(other.gameObject.name == "Sphere"){ myCube.Translate(0,-speed,0);
} } }
Answer by Mr.Jwolf · Jul 10, 2012 at 03:52 PM
I would say it would be easiest if you had two scripts. One script for the plane and one script for the cube.
PlaneScript:
using UnityEngine; using System.Collections;
public class PlaneScript : MonoBehaviour {
public GameObject Cube;
private CubeScript cubeScript;
public void Start()
{
cubeScript = (CubeScript) Cube.GetComponent(typeof(CubeScript));
}
public void OnTriggerEnter(Collider other){
if(other.gameObject.name == "Sphere")
{
cubeScript.Fall();
}
}
}
CubeScript:
using UnityEngine; using System.Collections;
public class CubeScript : MonoBehaviour {
private bool IsFalling = false;
public float speed = 1;
// Update is called once per frame
void Update () {
if(IsFalling)
{
transform.Translate(0,-speed * Time.deltaTime,0);
}
}
public void Fall()
{
IsFalling = true;
}
}
Remember OnTriggerEnter is only called if you have checked the "IsTrigger" on the planes collider, and the plane does not trigger if the Sphere is hitting the plane from behind.
Can you mark it as an answered then? The little thumps up beside the answer :)