首页 > 解决方案 > 'Random' 是 'UnityEngine.Random' 和 'System.Random' 之间的模棱两可的引用,我的错误在哪里?

问题描述

脚本是:

public class  : MonoBehaviour
{
    
public GameObject prefabEnemy;

    public Vector2 limitMin;
    public Vector2 limitMax;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(CreateEnemy());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator CreateEnemy()
    {
        while(true)
        {
            float r = Random.Range(limitMin.x, limitMax.x);
            Vector2 creatingPoint = new Vector2(r, limitMin.y);

            Instantiate(prefabEnemy, creatingPoint, Quaternion.identity);

            float creatingTime = Random.Range(0.5f, 3.0f);
            yield return new WaitForSeconds(creatingTime);
        }
    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawLine(limitMin, limitMax);
    }
}

错误是:

Assets\Scenes\EnemyCreate.cs(29,23): error CS0104: 'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'

标签: c#visual-studiounity3d

解决方案


Random在 2 个不同的库中使用, onSystem和 in UnityEngine,因此您必须指定要使用的库。

为此,您可以指定它键入:

using UnityEngine;

或者

using System;

在脚本的顶部。如果直接键入要引用的随机数,也可以避免“使用”,例如:

float r = UnityEngine.Random.Range(limitMin.x, limitMax.x);

推荐阅读