0
\$\begingroup\$

I'm trying to create a infinite racing game. I have a RoadSystem game object that instantiates a slab of road. On awake about 8 slabs are created. I'm trying to create a system where once the car passes the second or the third slab, the first slab is destroyed and then a new one is added at the end. I'm unable to get the index of the slabs. This is the code I have attached to a trigger which is just an empty gameobject with a box collider attached:

public class AddRemoveRoadSlab : MonoBehaviour {

  Public Road road

  private void OnTriggerExit(Collider other)
   {
      if (other.gameObject.tag == "RoadSlab"){
      Debug.Log(road.GetComponent<Transform>().GetSiblingIndex());
   } 
}

What the debug.log statement is printing is the index of the Road gameobject in the Hierarchy that includes the camera, direction light etc. I want to get the index of the children of the Road gameobject. Can someone please help?

Screenshot

EDIT

Here is a screenshot of how the Road and slab are configured. The road script generates the slabs. The slabs are just unity plane objects.

Screenshot1

\$\endgroup\$
2
  • \$\begingroup\$ Can you show us how the Road and Slab objects are configured in the Inspector? Presumably you tried outputting the index of the collider passed as the other argument? \$\endgroup\$ – DMGregory Jun 19 '20 at 13:07
  • \$\begingroup\$ I have added the screenshot. I would like to get the index of the 2nd or 3rd slab that is generated. But not able to get the index of the slabs. What I get is the index of the road gameobject in the hierarchy in this case I get 3. If I move the road game object to the bottom, then the index becomes 4. I want to be able to get the index of the slabs that get instantiated under the road gameobject. \$\endgroup\$ – single arrow games Jun 19 '20 at 16:15
0
\$\begingroup\$

It looks like you meant to write this:

private void OnTriggerExit(Collider other)
{
   if (other.CompareTag("RoadSlab")){
   Debug.Log(other.transform.GetSiblingIndex());
} 

You want the index of whichever collider you're interacting with, not the single road stored in your member variable.

\$\endgroup\$
1
  • \$\begingroup\$ thanks a lot for this....its working fine now... \$\endgroup\$ – single arrow games Jun 19 '20 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.