Search Unity

Simple script problem.

Discussion in 'Scripting' started by Woleth, Jan 22, 2018.

  1. Woleth

    Woleth

    Joined:
    Jan 22, 2018
    Posts:
    6
    I'm currently working on a rock that moves in a random direction but I can't make it work.

    Here's the script:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RockController : MonoBehaviour {
    5.  
    6.     private Rigidbody myRigidbody;
    7.     public int speed;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.         myRigidbody = GetComponent<Rigidbody>();
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Awake () {
    16.         int x = Random.Range (-1, 1);
    17.         int z = Random.Range (-1, 1);
    18.         Vector3 direc = new Vector3 (x, 0f, z);
    19.         myRigidbody.AddForce (direc * speed);
    20.     }
    21. }
    22.  
    And the error message:

     
  2. BubyMB

    BubyMB

    Joined:
    Jun 6, 2016
    Posts:
    140
  3. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    The actual problem is that Awake is always called before Start. So you've got a slightly wrong order there.
     
    Woleth likes this.
  4. Woleth

    Woleth

    Joined:
    Jan 22, 2018
    Posts:
    6
    So if I want to apply that force just once at the very start of the game, what should I use instead of Awake?
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You have to switch the methods around. Turn your start in Awake () and your awake into Start()
     
    Woleth likes this.
  6. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Code (CSharp):
    1.  
    2. public class RockController : MonoBehaviour {
    3.     private Rigidbody myRigidbody;
    4.     public int speed;
    5.     Vector3 direc;
    6.  
    7.     // Use this for initialization
    8.     void Start () {
    9.         myRigidbody = GetComponent<Rigidbody>();
    10.         int x = Random.Range (-1, 1);
    11.         int z = Random.Range (-1, 1);
    12.         direc = new Vector3 (x, 0f, z);
    13.     }
    14.  
    15.     // FixedUpdate is called once per physics frame
    16.     void FixedUpdate() {//ADD SPEED EVERY PHYSICS FRAME
    17.    
    18.         myRigidbody.AddForce (direc * speed);
    19.     }
    20. }
    Look up the ForceMode variable for the AddForce method.
    also, if your drag is zero and you keep speeding it up, you're gonna have a bad day.
     
    Last edited: Jan 23, 2018
  7. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Turn Update into FixedUpdate :p
     
    SparrowGS likes this.
  8. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Whoops, sorry, haha.