[英]How can I switch my code from UnityScript to C# (csharp)?
此脚本(代码)在 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;
}
}
这确实是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.