isMayoAVariable isMayoAVariable - 3 years ago 105
C# Question

WaitForSeconds Error in Unity5

I am trying to set up a simple script where if I collide with an object (just a simple box for now) then it triggers text to show on the screen with the "zone" name.

I'm getting a script error and I can't seem to figure out what it's telling me to do. I've tried to look at various tutorials but what keeps coming up is something static like a player name or score.

I want the text to fade after a bit, hence the extra function at the end that I am trying to pass the zone name to. I am attaching this script to each zone trigger.

Here's my code:

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

public class ZoneAnnounce : MonoBehaviour {

// Text Object
private Text zoneNameText;

// Exposed Text Variable
public string zoneName = "Unknown";

void OnCollisionEnter (Collision col) {

if ( col.gameObject.name == "Player" ) {
StartCoroutine(showZoneInfo(zoneName));
}

}

IEnumerator showZoneInfo (string zoneName) {

zoneNameText.text = zoneName;

yield return WaitForSeconds(3);

}

}


and here's the error I am getting:


Assets/ZoneAnnounce.cs(26,16): error CS0119: Expression denotes a type, where a variable, value or method group was expected

Answer Source

The problem is here: yield return WaitForSeconds(3);

WaitForSeconds is class. To yield it you have to create new instance of it. This can be done by simply adding the new keyword before WaitForSeconds.

Change that to yield return new WaitForSeconds(3);


If you already know the time(3 seconds) to wait, you can create new instance of WaitForSeconds then use it without the new keyword.

WaitForSeconds waitTime = new WaitForSeconds(3);
IEnumerator showZoneInfo(string zoneName)
{

    zoneNameText.text = zoneName;
    yield return waitTime;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download