簡體   English   中英

Unity C# 錯誤:(12,47):錯誤 CS1503:參數 2:無法從 &#39;System.Collections.Generic.List 轉換<UnityEngine.GameObject> &#39; 浮&#39;

[英]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 }

好的,如您所說,您只是想通過

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);
}

這也比重復訪問對象的數組和/或屬性更有效

這些錯誤告訴您您嘗試將 GameObjects 列為 float 並且它發生在這里:

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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM