Unity C# error: (12,47): error CS1503: Argument 2: cannot convert from 'System.Collections.Generic.List<UnityEngine.GameObject>' to 'float'

Unity C# error: (12,47): error CS1503: Argument 2: cannot convert from 'System.Collections.Generic.List<UnityEngine.GameObject>' to 'float'

总的来说,我是编程新手。

使用另一个脚本,我将所有名为 spawnPointC 的游戏对象存储在列表“spawnPointC”中,这些游戏对象是从生成其他预制件时出现的。

我想从该列表中随机选择一个游戏对象,并存储它的位置,以便稍后在同一位置生成另一个对象。

我已经尝试了一些其他的东西,但我不知道我在做什么。

你会怎么做?

1  using System.Collections;
2  using System.Collections.Generic;
3  using UnityEngine;
4
5  public class CspList : MonoBehaviour
6  {
7    public List<GameObject> spawnPointsC;
8    [SerializeField] private GameObject goal;
9 
10   void Start()
11   {
12       GameObject spawnIndex = Random.Range(0, spawnPointsC);
13 
14      float pointX = spawnIndex.transform.position.x;
15      float pointY = spawnIndex.transform.position.y;
16      float pointZ = spawnIndex.transform.position.z;
17
18      Vector3 pointSpawn = new Vector3(pointX, pointY, pointZ);
19      Instantiate(goal, pointSpawn, Quaternion.identity);
20   }
21 }

错误告诉您您正在尝试将 GameObjects 列为浮动,它发生在此处:

GameObject spawnIndex = Random.Range(0, spawnPointsC.Count);

我不太确定你为什么要尝试这样做,但也许可以尝试使用 spawnPointsC.Count @derHugo 提到的。

试试这个:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CspList : MonoBehaviour
{
   public List<GameObject> spawnPointsC;
   [SerializeField] private GameObject goal;

   void Start()
   {
      int spawnIndex = Random.Range(0, spawnPointsC.Count);
     
      float pointX = spawnPointsC[spawnIndex].transform.position.x;
      float pointY = spawnPointsC[spawnIndex].transform.position.y;
      float pointZ = spawnPointsC[spawnIndex].transform.position.z;
     
      Vector3 pointSpawn = new Vector3(pointX, pointY, pointZ);
      Instantiate(goal, pointSpawn, Quaternion.identity);
  }
}

好的,正如您所说的,您只是想传入

spawnPointsC.Count

因为您需要项目的数量,而不是整个列表实例。

此外,对于索引,GameObject 类型没有任何意义。你想要一个 int 或简单的 var 因为编译器已经“知道” Random.Range 返回了什么,所以没有必要明确地告诉它它是一个 int

var spawnIndex = Random.Range(0, spawnPointsC.Count);

作为旁注,Vector3 是一个结构。您可以将代码缩短为

void Start()
{
    // this is an int!
    var spawnIndex = Random.Range(0, spawnPointsC.Count);
    //                          this returns the according GameObject item from the list
    //                          | 
    //                          |                   Now you access the Transform and it's position only ONCE
    //                          |                   |
    //                          v                   v
    var randomSpawnPoint = spawnPointsC[spawnIndex].transform.position;
      
    // Since Vector3 is a struct it is a COPY by VALUE
    // There is no need for using new, just pass it on
    Instantiate(goal, randomSpawnPoint, Quaternion.identity);
}

这也比重复访问对象的数组 and/or 属性更有效