Reputation: 189
I create instances of a prefab, (which is two rectangles with a gap in the middle), and if the player sprite collides with the collider in the gap, the score will increase.
I have a boxCollider2D on a prefab object, and want this collider as a public variable on a separate sprite, so I can access it on my script on the sprite.
So currently, col, is the collider the sprite is interacting with which is:
barrier(Clone) (UnityEngine.BoxCollider2D))
and my colliderBox is:
barrier (UnityEngine.BoxCollider2D)
So the only difference is one is from the prefab, and one is from the the objected created using the prefab.
void OnTriggerEnter2D(Collider2D col){
if (col.CompareTag ("barrier") && col != colliderBox) {
Debug.Log (col);
Debug.Log (colliderBox);
SceneManager.LoadScene (mainMenu);
}
}
Upvotes: 0
Views: 2581
Reputation: 4283
If I get it, you want to have your collider as a public variable, try something like:
public class PrefabObject: MonoBehaviour {
public BoxCollider2D boxCollider;
private void Start()
{
this.boxCollider = this.GetComponent<BoxCollider2D>();
}
}
public class OtherObject: MonoBehaviour {
public PrefabObject prefabObject;
private BoxCollider2D boxCollider;
private void Start()
{
this.boxCollider = prefabObject.boxCollider;
//or also this.boxCollider = prefabObject.GetComponent<BoxCollider2D>();
}
}
If there is no PrefabObject script attached to the GameObject that have the boxCollider2D, and only have the collider component attached, the OtherObject will be like:
public class OtherObject: MonoBehaviour {
public GameObject prefabObject; //Here is the change!
private BoxCollider2D boxCollider;
private void Start()
{
this.boxCollider = prefabObject.GetComponent<BoxCollider2D>();
}
}
Upvotes: 2