Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Still not sure how GetComponent works

Discussion in 'Scripting' started by TwoCPM, Jun 29, 2016.

  1. TwoCPM

    TwoCPM

    Joined:
    Dec 5, 2015
    Posts:
    2
    using UnityEngine;
    using System.Collections;

    public class WheelSuspension : MonoBehaviour {

    public GameObject other;
    public Rigidbody rb = GetComponent<Rigidbody>();
    public float thrust = 20f;

    void OnTriggerStay()
    {
    rb.AddForce(-transform.up * thrust);
    }
    }

    This is my code to add a force to wheels and create suspension because I don't want the wheels to rub against the car body. When I try to play the game it gives me this error:
    Assets/WheelSuspension.cs(7,27): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.GetComponent(System.Type)'
    Would somebody be able to help me with this and clarify GetComponent for me?
     
  2. jaasso

    jaasso

    Joined:
    Jun 19, 2013
    Posts:
    64
    youll have to do it elsewhere for example in Start
    Code (CSharp):
    1. public Rigidbody rb;
    2. void Start()
    3. {
    4. rb=GetComponent<Rigidbody>();
    5. }
     
    Last edited: Jun 29, 2016
  3. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    956
    When you call GetComponent where you did there, it's called before the constructor for that class is run. Now in this case, Unity is handling the constructor and creation of the game object and its components. Unity needs to be able to fully create the object and its components before allowing you to use GetComponent. The start and awake methods give you a place to write code after the object has been fully created, making jaasso's answer correct.
     
  4. TwoCPM

    TwoCPM

    Joined:
    Dec 5, 2015
    Posts:
    2
    Thank you!