Home > Blockchain >  Game object can't detect others when using collision.gameObject.tag in unity
Game object can't detect others when using collision.gameObject.tag in unity

Time:05-15

I have designed a scenario as below: I created an object spawner to collide with things tagged as "ob", using a boolean to manage the timing to spawn new obstacles. Nonetheless, after some testing, I found that it seemed like nothing had ever collided with one another(Judged by the strings I put in the if condition had never shown in the console.) Can't figure out why! Please HELP!!!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class newObSpawning : MonoBehaviour
{
    public GameObject[] oblist;
    private bool hasOb=true;
    public float adjustSpawnx;



void Update()
{
    if (!hasOb)
    {
        spawnObs();
        hasOb = true;
    }
          
}


private void OnTriggerEnter2D(Collider2D collision)
{
   if (collision.gameObject.CompareTag("ob"))
   {
       hasOb = true;
       Debug.Log("hasOb"); //just for testing
   }
}
private void OnTriggerExit2D(Collider2D collision)
{ 
   if (collision.gameObject.CompareTag("ob"))
   {
       hasOb = false;
       
       Debug.Log("hasOb");
   }
}
public void spawnObs()
{
    int i = Random.Range(0, oblist.Length);
    Debug.Log(i);
    float y = 7.87f; 
    GameObject newob = Instantiate(oblist[i], new Vector3(transform.position.x  adjustSpawnx,y,0), Quaternion.identity); 
}
}

obspawner carry a "follow player" script to move at the same pace as the player,and it went just well

CodePudding user response:

Your player doesn't seem to have a Rigidbody2D component. Add Rigidbody2D to your player. A collider can only emit OnTriggerEnter2D or OnTriggerExit2D events if there is a rigidbody on the object too

CodePudding user response:

You have to tag the object "ob" that you want to register the collision with, most probably, I think what you are searching for is the collision of your player with object spawner so tag the player with "ob".

  • Related