- Home /
setting a transform var to an object that collided
I just want the object to identify surrounding objects inside a collider and i thought of this script (C Sharp) to do so:
using UnityEngine;
using System.Collections;
public class generatorScript : MonoBehaviour {
Transform structureLink;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter (Collision[] hit) {
for (int i = 0; i < hit.Length; i++){
if (hit[i].transform.tag =="structure"){
structureLink = hit[i].transform;
}
}
}
}
anyway there is a warning that says: Assets/generatorScript.cs(6,19): warning CS0414: The private field `generatorScript.structureLink' is assigned but its value is never used
and an error that says:Script error: OnCollisionEnter This message parameter has to be of type: Collision The message will be ignored.
any help is much apriciated thank you
Answer by robertbu · Oct 27, 2013 at 04:29 AM
OnCollisionEnter() has a collision as a parameter, not an array of collisions. If your object first collides with multiple object in a single frame, you will get multipe OnCollisionEnter() calls during that frame, one for each object you collided with. A collision has the transform of the object you collided with.
void OnCollisionEnter (Collision collision) {
if (collision.transform.name =="structure"){
structureLink = collision.transform;
}
}