- Home /
Question by
$$anonymous$$ · Jul 01, 2013 at 09:47 AM ·
c#collisionobjects
Help in solving mistake in my code
I have made scripts Test1 and Test2. Test1 script is looking for objects with script Test2, and when collides, variables are equating. But it works only 1 time. Thanks.
public class Test1 : MonoBehaviour {
public string myName;
public Test2[] Cubes;
// Use this for initialization
void Start ()
{
Cubes = FindObjectsOfType(typeof(Test2)) as Test2[];
}
void OnCollisionEnter()
{
for(int i = 0;i<Cubes.Length;i++)
{
myName = Cubes[i].name;
}
}
// Update is called once per frame
void Update ()
{
Debug.Log(myName);
}
}
public class Test2 : MonoBehaviour {
public string name = "Name";
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
Comment
Your finding objects of the type "Test2" you should be better off doing this:
Cubes = FindObjectsByTag("yourCubeTagHere");
simply replace yourCubeTagHere with whatever tag the cubes have. Hope this helps!Also, OnCollisionEnter only get called if the cubes have a non-kinematic rigidbody attached to them :)!
This wont work,because i wont have access to variables?
Best Answer
Answer by $$anonymous$$ · Jul 01, 2013 at 11:59 AM
Found information at http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html .
This is my solution :)
void OnCollisionEnter(Collision collider)
{
myName = collider.gameObject.GetComponent<Test2>().name;
}