Skip to main content
 首页 » 编程设计

c#之如何随机化对象的位置

2024年02月05日10Renyi-Fan

这是一些代码,用于实例化两种不同类型的预制件并将它们放置在随机位置。预制件实例化,但不随机实例化。我怎样才能解决这个问题???

using UnityEngine; 
using System.Collections; 
 
public class Spawner : MonoBehaviour { 
// Use this for initialization 
    void Start () { 
        InvokeRepeating ("SpawnAThing", 3.0f, 3.0f); 
    } 
 
// Update is called once per frame 
    void Update () { 
 
    } 
    void SpawnAThing(){ 
        GameObject x=null; 
        int z = Random.Range (0, 2); 
        switch (z) { 
        case 0: 
            x = (GameObject)Instantiate(Resources.Load("BadCircle"));; 
            break; 
        case 1: 
            x = (GameObject)Instantiate(Resources.Load("GoodCircle")); 
            break; 
        } 
        x.transform.position.Set (Random.Range (-Screen.width, Screen.width), Random.Range (-Screen.height, Screen.height), 0.0f); 
    } 
} 

请您参考如下方法:

由于使用了 transform.position.Set()

,您的代码无法正常工作

position.Set() 无法修改位置,因为它不返回该位置的引用。它返回一个副本。

直接用x.transform.position = new Vector3(x,y,z);修改变换

所以你所要做的就是替换

x.transform.position.Set (Random.Range (-Screen.width, Screen.width), Random.Range (-Screen.height, Screen.height), 0.0f); 

与

x.transform.position = new Vector3(Random.Range(-Screen.width, Screen.width), Random.Range(-Screen.height, Screen.height), 0.0f); 

编辑:

您现在看不到它,因为 Screen.width 和 Screen.height 离屏幕太远了。您必须使用 Camera.main.ViewportToWorldPoint 将 view 转换为 world 点,然后您可以使用 0 到 >1 代表屏幕,.5 是中间点。 如果您没有看到它,请减少传递到 Z 轴的 15。

  x.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Camera.main.nearClipPlane + 15f));