Search code examples
javascriptunity3d-2dtools

Issues adding force to a newly instantiated GameObject in Unity 5.3


I am making a 2D game in Unity 5.3 and I am having trouble using AddForce() on a GameObject that I have just Instantiated from a prefab. I am also getting a Syntax Error on the semicolon on line 12. In addition to this Syntax Error, Unity is complaining about the last three characters on this line. (Not including the comment) The javascript code is below:

#pragma strict

var Toast : GameObject;
var ToastSpawner : GameObject;

function Start() {
    InvokeRepeating("spawnToast", 3, 1);
}

function spawnToast() {
    var toastClone = Instantiate(Toast, Vector3 (0,-2,0), Quaternion.identity) as GameObject;
    var rb = toastClone.GetComponent<Rigidbody2D>(); //Line 13
    rb.AddForce(Vector3.up * 1000);
}

Any help is appreciated! :)


Solution

  • I have solved my problem by making a new script attached to the prefab that handles the AddForce() function. Code below.

    Script to spawn toast:

    #pragma strict
    
    var Toast : GameObject;
    var ToastSpawner : GameObject;
    
    function Start() {
        InvokeRepeating("spawnToast", 0, 1);
    }
    
    function spawnToast() {
        var toastClone = Instantiate(Toast, ToastSpawner.transform.position, Quaternion.identity);
    }
    

    Script to move toast:

    #pragma strict
    
    var rb : Rigidbody2D;
    
    function Start () {
        Invoke("moveToast", .5);
    }
    
    function moveToast () {
        rb.AddForce(Vector2 (0,5), ForceMode2D.Impulse);
    }