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. Dismiss Notice

Resolved AddForce on array of Instantiated objects not working

Discussion in '2D' started by c4mino, May 5, 2021.

  1. c4mino

    c4mino

    Joined:
    Nov 26, 2019
    Posts:
    10
    Thanks for all the help so far everyone, Unity Community rules.

    Can anyone tell me what on earth I am missing in my code? I am trying to addforce to a gameobject's rigidbody2d after I instantiate it, but I cannot get force to apply. I've looked at similar threads but haven't got their solutions to work for me.

    The rigidbody2d is on the instantiated object's child.

    Thanks in advance!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class InstantiateLoot : MonoBehaviour
    6. {
    7.     [SerializeField] private float dropHeight;
    8.     [SerializeField] private GameObject[] lootDrop;
    9.     [SerializeField] private int lootChancePercentage;  
    10.  
    11.     private int roll;
    12.  
    13.     public void DropLoot()
    14.     {
    15.         foreach (GameObject loot in lootDrop)
    16.         {
    17.             roll = Random.Range(1, 101);
    18.  
    19.             if (roll <= lootChancePercentage)
    20.             {
    21.                 Instantiate(loot, (transform.position + new Vector3(0, dropHeight, 0)), Quaternion.identity);
    22.                 Rigidbody2D rb = loot.GetComponentInChildren<Rigidbody2D>();
    23.                 rb.AddForce(new Vector2(100, 100));
    24.             }
    25.         }
    26.     }
    27. }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Same problem as another thread I responded to here:
    https://forum.unity.com/threads/assigning-variables-to-instantiated-objects.1102474/#post-7096375

    You're accessing the prefab's Rigidbody2D component, not the newly created instance of it in the scene.
    Instantiate
    returns the instance that was created, which is what you want to use instead:
    Code (CSharp):
    1. GameObject instance = Instantiate(loot, (transform.position + new Vector3(0, dropHeight, 0)), Quaternion.identity);
    2. Rigidbody2D rb = instance.GetComponentInChildren<Rigidbody2D>();
    3. rb.AddForce(new Vector2(100, 100));
     
    c4mino likes this.
  3. c4mino

    c4mino

    Joined:
    Nov 26, 2019
    Posts:
    10
    Thank you, thank you, thank you. You guys that take the time to help us beginners are amazing.