Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Trigger issue

Discussion in 'Scripting' started by Straydivarius, Sep 5, 2023.

  1. Straydivarius

    Straydivarius

    Joined:
    May 4, 2021
    Posts:
    4
    Hi guys! I' a noob in the scripting world and i'm tryng to do something but i'm stuck.
    I explain to you:
    My intention is that when the player approaches the rat object, the rat moves and that when the player moves away, the rat stops.
    I have added a child object to the rat (RatTrigger) which determines the action when it is traversed. I have managed to turn the spriterenderer and change the animation from idle to run, but I have not been able to get the rat to move. Can you give me a hand?
    I attach the scripts.
    Thanks in advance!


    RatController script.png RatTrigger script.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Absent from the above is all the OTHER things that must happen to get a trigger callback.

    Start with the requirements as outlined in the docs for the flavor(s) of OnTrigger you want.

    ALSO, for future reference:

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - ONLY post the relevant code, and then refer to it in your discussion.
     
  3. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    531
    My first recommendation is to add some logging so you can verify your assumptions. Like is other.tag == "Player" for instance.

    I'm a bit curious about the RatController being a singleton but more importantly I tend to think the behavior coded in the RatTrigger should be part of the RatController at least to begin with and should never be in an OnTrigger event. The event triggers some code but generally shouldn't contain the actual code. It makes it harder to test since only the trigger enter can set it off.

    In any case if you move the settings you are setting into a public method in the RatController you code toggle it on and off at will.
     
    Straydivarius likes this.
  4. Straydivarius

    Straydivarius

    Joined:
    May 4, 2021
    Posts:
    4
    Ok, thank you. Have a nice day!
     
  5. Straydivarius

    Straydivarius

    Joined:
    May 4, 2021
    Posts:
    4
    Thanks for your help.