Search Unity

Get GameObject (What's wrong here?)

Discussion in 'Scripting' started by MICKDOii, Jul 29, 2015.

  1. MICKDOii

    MICKDOii

    Joined:
    Jan 12, 2015
    Posts:
    69
    I've tried to alter a material script to get game objects instead.

    Not quite working as planned.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RandomMaterial : MonoBehaviour {
    5.    
    6.     public GameObject[] gameObject;
    7.     int current;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.     }
    12.    
    13.     // Update is called once per frame
    14.     public void Switch () {
    15.         current++;
    16.         if (current >= gameObject.Length)
    17.             current = 0;
    18.         GetComponent<GameObject> = gameObject[current];
    19.     }
    20. }
    21.  
    Original Code


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RandomMaterial : MonoBehaviour {
    5.    
    6.     public Material[] materials;
    7.     int current;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.     }
    12.    
    13.     // Update is called once per frame
    14.     public void Switch () {
    15.         current++;
    16.         if (current >= materials.Length)
    17.             current = 0;
    18.         GetComponent<Renderer>().material = materials[current];
    19.     }
    20. }
    21.  
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    game objects aren't components, they are the things that components are attached to.

    what are you trying to do?
     
  3. matthewseaward

    matthewseaward

    Joined:
    Apr 12, 2013
    Posts:
    50
    So you want to get a gameobject from an array?
    What do you want to do with it when you've got it - assign it to a variable?

    Gameobjects cannot be components but instead they contain components. You call 'GetComponent' on a Gameobject.

    Does this fit what you want?


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class RandomMaterial : MonoBehaviour {
    4.  
    5.     public GameObject[] gameObject;
    6.     int current;
    7.     private GameObject selectedObject;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     public void Switch () {
    15.         current++;
    16.         if (current >= gameObject.Length)
    17.             current = 0;
    18.        selectedObject = gameObject[current];
    19.     }
    20. }
    21.  
     
  4. garrido86

    garrido86

    Joined:
    Dec 17, 2013
    Posts:
    233
    Just a tip,always get the SharedMaterial and not the Material - otherwise you would make instances of said materials and break batching.