This script(code) it works fine in UnityScript, but now i want to switch it to C#. This is what I've got so far. I think there is a problem at "transform.position" and generating a "random position" for my character. Probably it's very simple thing, but I'm a beginner in C#, so please help me out.
public class AntScript : MonoBehaviour
{
public GameObject ant;
public GameObject scoreText;
public GameObject livesText;
public double walkingSpeed = 0.0f;
public int livesNumber = 3;
public int scoreNumber = 0;
float x;
float y;
void Start() { ant = GameObject.Find("Ant");
scoreText = GameObject.Find("Score");
livesText = GameObject.Find("Lives");
//Initialize the GUI components
livesText.GetComponent<Text>().text = "Lives Remaining: " + livesNumber;
scoreText.GetComponent<Text>().text = "Score: " + scoreNumber;
//Place the ant in a random position on start of the game
ant.transform.position.x = generateX();
ant.transform.position.y = generateY();
}
void Update()
{
Vector3 p = transform.position;
if (ant.transform.position.y < -4.35 && livesNumber > 0)
{
livesNumber -= 1;
livesText.GetComponent<Text>().text = "Lives Remaining: " + livesNumber;
generateCoordinates();
}
else if (ant.transform.position.y < -4.35 && livesNumber == 0)
{
Destroy(GameObject.Find("Ant"));
gameOver();
}
else
{
ant.transform.position.y -= walkingSpeed;
}
}
void gameOver()
{
Application.LoadLevel("GameOver");
}
//Generates random x
void generateX()
{
x = Random.Range(-2.54f, 2.54f);
//return x;
}
//Generates random y
void generateY()
{
y = Random.Range(-4.0f, 3.8f);
//return y;
}
//Move the "Ant" to the new coordiantess
void generateCoordinates()
{
//You clicked it!
scoreNumber += 1;
//Update the score display
scoreText.GetComponent<Text>().text = "Score: " + scoreNumber;
ant.transform.position.x = generateX();
ant.transform.position.y = generateY();
}
//If tapped or clicked
void OnMouseDown()
{
//Place the ant at another point
generateCoordinates();
//Increase the walking speed by 0.01
walkingSpeed += 0.01f;
}
}
This is indeed a quirk of C#, it took me a while to get it at first
The problem is, transform.position is not a field, its a setter/getter (its a pair of methods internally, imagine it as Vector3 GetPosition() and SetPosition(Vector3), wchich means you need to pass a whole struct into it, you cannot just set x or y (as the method cannot be called until you have all the parameters. The workaround is really simple fortunately
Vector3 temp = ant.transform.position; // use a getter
temp.x = generateX(); // modify a struct
temp.y = generateY();
ant.transform.position=temp; // use a setter
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.