Hello, I need help with a simple script. I am a super noob and I am trying to write a script to make the player move by fixed steps (like in a grid) using c# and unity 4.3. I tried (following a wiki example) to use a coroutine because I want to stop receiving input from the keyboard until the movement to the next position in the grid is done, but I keep getting compiler errors. Here is what I’ve done so far:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public GameObject player;
public float speed;
private Vector3 p;
void Start ()
{
// player position
p = player.transform.position;
//starts coroutine CoUpdate()
StartCoroutine(CoUpdate());
}
//coroutine
IEnumerator CoUpdate()
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
yield return move(Vector3.right);
}
else if (Input.GetKeyDown(KeyCode.LeftArrow))
{
yield return move(Vector3e.left);
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
yield return move(Vector3.forward);
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
yield return move(Vector3.back);
}
else
{
yield return null;
}
}
void move(Vector3 direction)
{
transform.Translate(direction * speed * Time.deltaTime, Space.Self);
}
}
With this code compiler complains that "cannot convert type void to object’, and even if I add
new after yield it throws errors. How can I fix it?
Thank you, now It works, even if not as good as I expected. The problem is I had to write "StartCoroutine(CoUpdate());" inside of "void Update ()" otherwise it won't work.
– LidiaAnd then, if I press 3 times rightarrow and then 3 times leftarrow it doesn't come back in the exact same position. What am I doing wrong?
– LidiaNevermind, I found the correct answer by rewriting the code without Time.deltaTime and correcting some mistakes. I'll give you the correct answer anyway.
– LidiaI am glad it now works.
– raimon.massanetWhat corrections did you make to make this work? This question is the closest thing I've found to a solution to this problem, and I'm stuck at the point where the character moves, but inconsistantly after moving the coroutine to update like you did.
– KnightsHouseGames