此脚本(代码)在UnityScript中可以正常工作,但现在我想将其切换为C#。这就是到目前为止。我认为“ transform.position”存在问题,并且为我的角色生成了“随机位置”。 可能这很简单,但是我是C#的初学者,所以请帮助我。
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;
}
}
答案 0 :(得分:2)
这确实是C#的怪癖,我花了一些时间才刚开始使用它
问题是,transform.position不是字段,而是一个setter / getter(内部是一对方法,将其想象为Vector3 GetPosition()和SetPosition(Vector3)),这意味着您需要传递整个结构不能在其中设置x或y(因为只有拥有所有参数,该方法才能被调用。 幸运的是,解决方法非常简单
Vector3 temp = ant.transform.position; // use a getter
temp.x = generateX(); // modify a struct
temp.y = generateY();
ant.transform.position=temp; // use a setter