Search Unity

Problem with if and SetActive

Discussion in 'Scripting' started by Cristaccio, Nov 20, 2017.

  1. Cristaccio

    Cristaccio

    Joined:
    Nov 20, 2017
    Posts:
    3
    Good morning, recently i started to make a game where, when the player enter in a trigger, a text appear and say him "Press F", when he press F a new message appears "Random Message" and the message that there where first disappears... but there is a problem... when i press F the old message doesnt disappear... why?
    Here's the script, (i applied this to the trigger)

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

    public class Livello1Discorsi : MonoBehaviour {

    public GameObject Subject;
    public GameObject Preview;

    void OnTriggerStay()
    {
    Preview.SetActive(true);

    if(Input.GetKeyDown(KeyCode.F))
    {
    Subject.SetActive(true);
    Preview.SetActive(false);
    }
    }

    void OnTriggerExit()
    {
    Subject.SetActive(false);
    }
    }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    On trigger stay is like a continuous loop while the object is inside the zone. Input. GetKeyDown, only fires once, so as soon as it's finished, Preview.SetActive(true) gets activated over and over in the loop. You should probably use OnTriggerEnter to set preview active.
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    here is what I might do

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Livello1Discorsi : MonoBehaviour
    6. {
    7.  
    8. public GameObject Subject;
    9. public GameObject Preview;
    10.  
    11.  
    12.     void OnTriggerEnter()
    13.     {
    14.         Preview.SetActive(true);
    15.     }
    16.  
    17.     void OnTriggerExit()
    18.     {
    19.         Subject.SetActive(false);
    20.         Preview.SetActive(false);
    21.     }
    22.  
    23.     void Update()
    24.     {
    25.         if(Input.GetKeyDown(KeyCode.F) && Preview.activeSelf == true)
    26.         {
    27.             Subject.SetActive(true);
    28.             Preview.SetActive(false);
    29.         }
    30.     }
    31. }
     
    ZetroEUW and KelsoMRK like this.
  4. Cristaccio

    Cristaccio

    Joined:
    Nov 20, 2017
    Posts:
    3
    Thanks dude, sorry if it's a stupid question but im new in game developing :D