- Home /
im trying to make it if a specific item collides with a cube it flashes red but it keeps comming up with an error
on unity i am trying to make it if a specific item collides with a cube it flashes red but it keeps comming up with an error
; expected or = (cannot specify constructor arguments in declaration)
and it highlights the "yield WaitForSeconds(0.5);" row can somebody tell me whats wrong?
this is the code
using UnityEngine;
using System.Collections;
public class swordCollideWithEnemybasic : MonoBehaviour {
private int enehealth = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter (Collision hit) {
if (enehealth <= 0)
if (hit.gameObject.name == "sword")
gameObject.renderer.material.color = Color.red;
yield WaitForSeconds(0.5);
gameObject.renderer.material.color = Color.grey;
}
Answer by Razacx · Jul 11, 2014 at 12:21 PM
It is impossible to call a yield outside of a co-routine to my knowledge. You might want to remove the following code from OnCollisionEnter and put in in a coroutine:
yield WaitForSeconds(0.5);
gameObject.renderer.material.color = Color.grey;
Also, yield WaitForSeconds() is javascript syntax, in c# it would be done as the following:
yield return new WaitForSeconds();
I also think you have made some mistakes with the parentheses of the if-statements in OnCollisionEnter.
Using all of this information, you should end up with something like this:
using UnityEngine;
using System.Collections;
public class swordCollideWithEnemybasic : MonoBehaviour {
private int enehealth = 0;
// Update is called once per frame
void OnCollisionEnter (Collision hit) {
if (enehealth <= 0) {
if (hit.gameObject.name == "sword") {
gameObject.renderer.material.color = Color.red;
StartCoroutine(turnGreyDelayed());
}
}
}
//Coroutine for setting color back to grey after 0.5 seconds
IENumerator turnGreyDelayed() {
yield return new WaitForSeconds(0.5f);
gameObject.renderer.material.color = Color.grey;
}
Answer by Landern · Jul 11, 2014 at 12:25 PM
As @josh-naylor stated and is indicating with his comment, your OnCollisionEnter method is mal-formed, and i'm also going to say your if statements are not blocked correctly. If you don't use curly braces, an if statement will only execute the next line of code if it the expression is true.
using UnityEngine;
using System.Collections;
public class swordCollideWithEnemybasic : MonoBehaviour {
private int enehealth = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
IEnumerator OnCollisionEnter (Collision hit) {
if (enehealth <= 0) {
if (hit.gameObject.name == "sword") {
gameObject.renderer.material.color = Color.red;
yield return new WaitForSeconds(0.5);
gameObject.renderer.material.color = Color.grey;
}
}
}
The method in c# yielding the waitforseconds needs to return IEnumerator/IEnumerable.
Your answer
![](https://koobas.hobune.stream/wayback/20220613153803im_/https://answers.unity.com/themes/thub/images/avi.jpg)