【问题标题】:A 'using namespace' directive can only be applied to namespaces; 'Random' is a type not a namespace. Consider a 'using static' instead“使用命名空间”指令只能应用于命名空间; “随机”是一种类型而不是命名空间。考虑使用“使用静态”代替
【发布时间】:2020-10-01 09:10:57
【问题描述】:

这是我尝试在 Unity3D 中使用我的代码之一时遇到的错误。 以下是我使用的代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.Random;
public class BackgroundTile : MonoBehaviour
{
    public GameObject[] dots;

    // Start is called before the first frame update
    void Start()
    {
        Initialize();
    }

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

    void Initialize()
    {
        int dotToUse = Random.Range(0, dots.Length);
        GameObject dot = Instantiate(dots[dotToUse], transform.position, Quaternion.identity);
        dot.transform.parent = this.transform;
        dot.name = this.GameObject.name;
    }
}

你们能告诉我哪里错了,以便我更正我的代码。

【问题讨论】:

  • 错误信息已经很明确了,不知道可以添加什么。只需删除 using UnityEngine.Random; 行。

标签: c# .net unity3d


【解决方案1】:

UnityEngine.Random 是静态类,而不是命名空间。

要使用Random.Range,您只需为Random的命名空间添加using指令,即UnityEngine

你可以做的是添加一个静态 using 指令:

using static UnityEngine.Random;

通过这样做,您可以在对Random 的 staic 成员的任何调用中省略类型名称,例如:

int dotToUse = Range(0, dots.Length);

【讨论】:

  • 谢谢,这解决了我的问题,我得到的另一个问题是我收到一条警告:文件不一致,有些是 MacOS,有些是 windows。
  • @Deatus 我不确定是什么原因造成的;我会将其记录为一个新问题。
猜你喜欢
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2011-01-02
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多