I have this script
if (collision.gameObject == convey[0])
{
pointCube.transform.Translate(convey[].transform.forward * speed);
}
How do i get the convey number that the pointCube gameobject is touching, then get the forward vector of that convey?
Use the Unity inbuilt function:
// If the object is a trigger
void OnTriggerEnter (Collider other) {
}
// If the object is not a trigger
void OnCollisionEnter (Collision other) {
}
Then inside the function oyu want/ or both write:
// Check if it is the object I want
if (other == objectIAmLookingFor) {
// Get the forward transform
Vector forwardVec = other.transform.forward;
// Do with the forwardVec what you want
DoSomethingWithVec (forwardVec);
}
int i=convey.Length;
while(i>0){i–;
if (collision.gameObject == convey*)*
{print("my convey number is "+i);
pointCube.transform.Translate(convey_.transform.forward * speed);_
}}
If you only need to know whether the object hit is one of the convey elements, do the following:
void OnCollisionEnter (Collision other) {
GameObject hitObj = other.gameObject; // hitObj = the game object we collided with
foreach (GameObject conveyElement in convey){ // search it in the convey array
if (hitObj == conveyElement){
// if hitObj found in convey[], get its forward direction directly from it
pointCube.transform.Translate(hitObj.transform.forward * speed);
return; // and bye bye
}
}
}
Another solution would be to create a specific tag (“convey”) and assign it to all objects you’re currently listing in convey (you would not need this array anymore).
void OnCollisionEnter (Collision other) {
GameObject hitObj = other.gameObject; // hitObj = the game object we collided with
if (hitObj.CompareTag("convey")){ // is it an object tagged "convey"?
// yes, get its forward direction directly from it
pointCube.transform.Translate(hitObj.transform.forward * speed);
}
}
But if you really need to know the index of the hit object in the convey array, use @toddisarockstar answer.