Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Text with OnTriggerEnter2D(Collider2D collider)

Discussion in 'Scripting' started by ajcombest3, Mar 22, 2018.

  1. ajcombest3

    ajcombest3

    Joined:
    Mar 13, 2018
    Posts:
    27
    I have a text prefab with a 2d collider, rigid body and a script attached. It is instantiated by another script and when it collides with the player I need to do things based upon the text of the clone.

    The problem is I do not know how to check the text of the object that is colliding with the player.
    This is what I have and I am not sure where to go from here.

    Code (CSharp):
    1. public class LevelMech : MonoBehaviour {
    2.  
    3.     private void OnTriggerEnter2D(Collider2D collider) {
    4.         Player player = collider.gameObject.GetComponent<Player>();
    5.         if (player) {
    6.            // if (this.???Text = ? ) { I do not know what to do at this point
    7.  
    8.             }
    9.         }
    10.     }
    11. }
     
  2. ajcombest3

    ajcombest3

    Joined:
    Mar 13, 2018
    Posts:
    27
    I am getting the error "NullReferenceException:Object reference not set to an instance of an object
    Code (CSharp):
    1.     private void OnTriggerEnter2D(Collider2D collider) {
    2.         Player player = collider.gameObject.GetComponent<Player>();
    3.         if (player) {
    4.           if(this.gameObject.GetComponent<Text>().text == "Asteroid Field") {
    5.                 gameObject.GetComponent<AstroidSpawner>().RandomSpawn();            
    6.             }
    7.         }
    8.     }
    9. }
     
  3. ajcombest3

    ajcombest3

    Joined:
    Mar 13, 2018
    Posts:
    27
    Same error, not sure what i'm doing wrong

    Code (CSharp):
    1.     private void OnTriggerEnter2D(Collider2D collider) {
    2.         Player player = collider.gameObject.GetComponent<Player>();
    3.         Text text = gameObject.GetComponent<Text>();
    4.         if (player) {
    5.           if(text.text == "Asteroid Field") {
    6.                 gameObject.GetComponent<AstroidSpawner>().RandomSpawn();            
    7.             }
    8.         }
    9.     }
    10. }
    11.  
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    What is a text prefab? The Text component is for UI, not for a game object.
     
  5. hjohnsen

    hjohnsen

    Joined:
    Feb 4, 2018
    Posts:
    67
    Perhaps you just want collider.gameObject.name.