【问题标题】:My compiler tells me it cannot convert 'void' to 'string' I understand what this means, but not how to fix it [closed]我的编译器告诉我它不能将“void”转换为“string”我理解这意味着什么,但不知道如何修复它[关闭]
【发布时间】:2021-03-26 17:06:35
【问题描述】:

这里我试图在随机位置(在RandomPosOne()中定义)实例化定义的GameObject

但是我的编译器说

无法从“void”转换为“string”

public class Enemyspawner : MonoBehaviour
{
    public GameObject Elf;
 
    private void OnCollisionEnter2D(Collision2D collider)
    {
        if (collider.gameObject.CompareTag("SpawnTrigger1"))
        {
            InvokeRepeating((SpawnElfOne()), 2f, 3f);

        }
        void SpawnElfOne()
        {
            Instantiate(Elf, RandomPosOne(), Quaternion.identity);
        }
        
    }

    Vector2 RandomPosOne()
    {
        float x, y;
        x = Random.Range(-8.6f, 8.7f);
        y = Random.Range(3.05f, -3.36f);
        return new Vector2(x, y);
    }

    Vector2 RandomPosTwo()
    {
        float x, y;
        x = Random.Range(-8.8f, 8.8f);
        y = Random.Range(19f, 12.6f);
        return new Vector2(x, y);
    }

}

【问题讨论】:

  • 你在哪一行得到错误?

标签: c# string random instantiation void


【解决方案1】:

将本地 void 方法 SpawnElfOne 移出到实例中

并在调用InvokeRepeating时将目标方法名称作为string参数传递

public class Enemyspawner : MonoBehaviour {
    public GameObject Elf;
 
    private void OnCollisionEnter2D(Collision2D collider) {
        if (collider.gameObject.CompareTag("SpawnTrigger1")) {
            InvokeRepeating("SpawnElfOne", 2f, 3f);
        }           
    }

    void SpawnElfOne() {
        Instantiate(Elf, RandomPosOne(), Quaternion.identity);
    }
        
    Vector2 RandomPosOne() {
        float x, y;
        x = Random.Range(-8.6f, 8.7f);
        y = Random.Range(3.05f, -3.36f);
        return new Vector2(x, y);
    }

    Vector2 RandomPosTwo() {
        float x, y;
        x = Random.Range(-8.8f, 8.8f);
        y = Random.Range(19f, 12.6f);
        return new Vector2(x, y);
    }

}

【讨论】:

  • nameof(SpawnElfOne) 在这里不是更好吗?
  • @MathiasR.Jessen 是的,也可以。不确定使用的是什么版本的 C# OP,所以不想做任何假设。
  • 谢谢,效果很好,编译该脚本时的错误导致项目中的所有其他脚本都停止工作,因此您为我省去了很多痛苦。
猜你喜欢
  • 2020-08-09
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多