[英]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.