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

cannot set velocity or rotation outside on in Start()

Discussion in '2D' started by robby_stark, Jun 11, 2015.

  1. robby_stark

    robby_stark

    Joined:
    May 31, 2015
    Posts:
    1
    the Player object can instantiate Fireball Objects. if I put the code to set velocity in the Start() method, it works as intended. however I want to be able to set speed (and eventually other variables as well) through methods. why is this simple code not working? it instantiates a fireball with no speed.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Fireball : MonoBehaviour
    5. {
    6.     private Rigidbody2D myRigidBody;
    7.  
    8.     void Start ()
    9.     {      
    10.         myRigidBody = GetComponent<Rigidbody2D> ();          
    11.     }
    12.  
    13.     public void fire (float speed)
    14.     {
    15.         myRigidBody.velocity = new Vector2 (0, 1) * speed;
    16.     }
    17. }
     
  2. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    Use FixedUpdate() to change physics properties on the Rigidbody2D.
     
  3. Gardes

    Gardes

    Joined:
    Apr 7, 2015
    Posts:
    46
    And imo you should use AddForce instead of trying to set velocity directly.
     
  4. Pharan

    Pharan

    Joined:
    Oct 28, 2013
    Posts:
    102
    It should work though, even on Update.

    Are you sure fire is being called? Are you sure gravity isn't actually immediately overcoming the 1f upward velocity? Is your RigidBody2D set to kinematic?