gpt4 book ai didi

c# - 如何将我的代码从 UnityScript 切换到 C# (csharp)?

转载 作者:行者123 更新时间:2023-11-30 21:28:36 25 4
gpt4 key购买 nike

此脚本(代码)在 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

关于c# - 如何将我的代码从 UnityScript 切换到 C# (csharp)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56254688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com