简体   繁体   中英

unity c# set text true with GetMouseButtondown

I basicly just want to talk to an NPC. The text should show up once I pressed MouseButton(0) . With my current code the text stays as long as I hold the mouse button down.

if (Input.GetMouseButton(0) && Input.GetMouseButton(0) && cc.height < 20 && Vector3.Distance(Larry.transform.position, this.transform.position) < 10)
{
    text1.SetActive(true);

So how should this if statement look like if i want to see the text until Vector3.Distance(Larry.transform.position, this.transform.position) < 10 is not true anymore?

Assuming that code block is placed in eg Update where it is called every frame you simply have to leave the text enabled until you match the opposite condition

It also is enough to use Input.GetMouseButtonDown (fires only once at the beginning when mouse button is pressed) instead of Input.GetMouseButton (fires repeatedly every frame while mouse button stays pressed) to use only one call for enabling the text since it will stay enabled "automatically".

if (Input.GetMouseButtonDown(0) && cc.height < 20 && Vector3.Distance(Larry.transform.position, transform.position) < 10)
{
    // Enable the text
    text1.SetActive(true);
}
// Meanwhile the second condiction isn't matched 
// the text stays active anyway
// Use if else to avoid an unnecessary check
// since only one of the two conditions can be true at the same time
else if(Vector3.Distance(Larry.transform.position, transform.position) >= 10)
{
    // Disable the text
    text1.SetActive(false);
}

You just need to do the same but with the oposite of the Vector3.Distance<10 like this:

 if(Vector3.Distance(Larry.transform.position, this.transform.position) => 10)
     text1.SetActive(false);  

Oh, and you have a redundant Input.GetMouseButton(0) , I believe only calling it once should be enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM