Search Unity

Question when trying to add a GameObject to a list - CS1001: Identifier expected

Discussion in 'Scripting' started by alexb2008, Mar 12, 2023.

  1. alexb2008

    alexb2008

    Joined:
    Mar 16, 2022
    Posts:
    34
    I am still fairly new to C# but,
    I cannot figure out what my error is here. I am trying to add the GameObject that entered the collider to a list of GameObjects. initial thought would have been that maybe the 'other' is a collider or transform of sorts but I still don't think that makes sense but to be honest I am not sure. Any help much appreciated!
    (heres the whole code I have at the moment)
    Code (CSharp):
    1. public class craftingScript : MonoBehaviour
    2. {
    3.  
    4.     [SerializeField] private string pickuppableTag = "pickuppable";
    5.  
    6.     public GameObject leaf, stick, stone;
    7.  
    8.     public GameObject[] items;
    9.  
    10.     public GameObject[] r_string = leaf;
    11.  
    12.     void Update()
    13.     {
    14.        
    15.     }
    16.  
    17.     void OnCollisionEnter(Collider other)
    18.     {
    19.         if(other.transform.CompareTag(pickuppableTag))
    20.         {
    21.             items[] = new GameObject(other);
    22.         }
    23.     }
    24. }
     
  2. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    660
    Maybe im completely blind today, but i don't see a List anywhere. Just some arrays.


    Additionally, depending on your approach, OnCollision and OnTrigger are considerably different, and may require you to look at your use of rigidbody, or lack of.


    Code (CSharp):
    1. private List<GameObject> objectsList = new List<GameObject>();
    2.  
    3. private void AddGameObjectToList(GameObject _gameObject)
    4. {
    5.     objectsList.Add(_gameObject);
    6. }
     
    alexb2008 likes this.
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,934
    Code (CSharp):
    1. items[] = new GameObject(other);
    This isn't valid syntax.

    You need to provide an index to assign to a position in an array:
    Code (CSharp):
    1. items[0] = other.gameObject;
    However you should use a
    List<T>
    , rather than an array.
     
    alexb2008 and Homicide like this.
  4. alexb2008

    alexb2008

    Joined:
    Mar 16, 2022
    Posts:
    34
    I thought GameObject[] was a list... It isn't an array because throughout the code the length will change depending on how many items are inside the collider
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,934
    No... it's an array.

    Code (CSharp):
    1. // this is an array
    2. private GameObject[] gameObjectArray;
    3.  
    4. // this is a list
    5. private List<GameObject> gameObjectList;
    Google 'C# array' and 'C# list' and familiarise yourself with the differences.
     
    Bunny83, Chubzdoomer and alexb2008 like this.