- Home /
trying to define the last object I collided with and store it as a variable?
I want to take whatever object i just collided with and save it as "obj1". and if "obj1" is taken, i want to save it as "obj2". I tried this but it doesn't do anything. any suggestions?
using System.Collections;
public class DuplicationScript : MonoBehaviour {
public GameObject obj1;
public GameObject obj2;
GameObject newParentObj;
Rigidbody rB1;
Rigidbody rB2;
public bool hasFixedJoint;
public bool noHit;
public bool hasHit;
void Start () {
rB1 = obj1.GetComponent<Rigidbody>();
rB2 = obj2.GetComponent<Rigidbody>();
noHit = true;
}
void Update () {
if (Input.GetKeyDown(KeyCode.F) && hasFixedJoint == false)
{
obj1.AddComponent<FixedJoint>();
hasFixedJoint = true;
rB1.mass = .5f;
rB2.mass = .5f;
}
if (hasFixedJoint)
{
obj1.GetComponent<FixedJoint>().connectedBody = obj2.GetComponent<Rigidbody>();
}
}
void OnCollisionEnter(Collision hit){
if (noHit)
{
obj1 = hit.gameObject;
hasHit = true;
}
if (hasHit)
{
obj2 = hit.gameObject ;
}
}
}
Try adding a Debug.Log statement that prints the name of the object you collided with before storing it in either of the obj variables.
Also, make sure that the GameObject with this script has a collider (not any of its children), otherwise it will not detect a collision.
yeah i tried messing around with that, i couldn't really find a useful way to use debug.log in this situation.
Answer by meat5000 · Jul 29, 2015 at 02:18 AM
void OnCollisionEnter(Collision hit)
{
if (!obj1)
{
obj1 = hit.gameObject;
}
else if(!obj2)
{
obj2 = hit.gameObject;
}
}
This needs no boolean flags.
Answer by TonanBora · Jul 29, 2015 at 02:04 AM
I am not sure this has anything to do with your problem, but a better way of structuring your Collision method is like this:
if(noHit){
obj1 = hit.gameObject;
hasHit = true;
notHit = false; // You forgot this line
}else{ // if noHit is false
obj2 =- hit.gameObject;
}
In this code, if noHit is true, it sets the colliding gameObject to obj1, otherwise it sets it to obj2. The problem with your original code was that since noHit was not getting set to false, the second Game Object that caused a collision would get set to both obj1 and obj2 because both If statements would be checked and both would be true.