在Unity中填充列表和随机选择项目
本文关键字:随机 选择 项目 列表 Unity 填充 | 更新日期: 2023-09-27 17:52:54
我有一个Unity脚本PlayerController.cs与游戏登录和MyCity.cs,其中为MyCity定义了一个公共类。
我的目标是在PlayerController.cs中填充List。列表包含城市及其x,y,z Vector3坐标。
我的PlayerController脚本应该从我的列表中随机选择一个城市,并在我的SetTargetCity函数中使用它,这样它就可以用适当的Vector3坐标创建一个新的游戏对象。
我得到这个错误:
'名称mycities'在当前文档中不存在'
我做错了什么?为mycities创建一个公共变量无法达到目的....
MyCity.cs包含以下内容:
using UnityEngine;
using System.Collections;
public class MyCity
{
public string name;
public float xcor;
public float zcor;
public float ycor;
public MyCity(string newName, float newXcor, float newZcor, float newYcor)
{
name = newName;
xcor = newXcor;
zcor = newZcor;
ycor = newYcor;
}
}
然后PlayerController脚本看起来像这样:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerController : MonoBehaviour
{
public float speed;
public float smooth = 2.0F;
public GUIText countText;
public GUIText targetCity;
private int count;
public GameObject cityPrefab;
void Start()
{
List<MyCity> mycities = new List<MyCity>();
mycities.Add( new MyCity("Maastricht", -5F, 3F, -1F ));
mycities.Add( new MyCity("Breda", -6F, 3F, -2F));
mycities.Add( new MyCity("Amsterdam", -2F, 3F, 4F));
//WHAT ELSE DO I NEED TO DO TO THE ABOVE LIST SO THAT
//THE BELOW FUNCTION void SetTargetCity () WILL WORK?
// scoring points & display on screen (works)
count = 0;
SetCountText ();
}
// Player Movement (works)
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
Vector3 moveDirection= new Vector3 (moveHorizontal, 0, moveVertical);
if (moveDirection != Vector3.zero){
Quaternion newRotation = Quaternion.LookRotation(moveDirection * -1);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * smooth);
rigidbody.AddForce(movement * speed * Time.deltaTime);
}
}
// Score points by flying into city game object (works), switch off that target city game object (works), get new target city...(no idea)
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "City") {
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
SetTargetCity ();
}
}
void SetCountText ()
{
countText.text = "Passengers Picked up: " + count.ToString();
}
// BELOW IS WHERE THINGS GO WRONG.
void SetTargetCity ()
{
var randomCity = mycities[0];
targetCity.text = "Fly to: " + randomCity.name.ToString();
GameObject instancedCity=(GameObject)GameObject.Instantiate(cityPrefab);
instancedCity.transform.position=new Vector3(randomCity.xcor,randomCity.ycor,randomCity.zcor);
}
}
在Start
方法之外定义myCities
并像这样初始化它:
List<MyCity> mycities;
void Start()
{
mycities = new List<MyCity>();
...
}