How can i make a prefab instantiate another prefab?

36 views Asked by At

So basically, lets say i have a cannon, i wanted to make it shoot a cannonball(prefabs) and leave an explosion(prefab) at the place it collided.

example code for projectile:


using UnityEngine;

public class projectiles : MonoBehaviour
{
    

public int life;
    cannonball cannonball

    private void Awake()
    {

        Destroy(gameObject, life);
    }
    void OnCollisionEnter(Collision collision)
    {
        GameObject endeffect = Instantiate(explosion, body.position, body.rotation, spells);
        endeffectrb.transform.localscale*= cannonball.size;

        Destroy(gameObject);
    }
}
'''

example code for explosion:
'''
using UnityEngine;

public class cannonball: MonoBehaviour
{
    public GameObject ball;
    public Transform player;
    public Transform cam;

    public KeyCode shootkey = KeyCode.Mouse0;

    public float speed = 10;
    public float size= 10f;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(shootkey))
        {
            shoot();

        }
    }
    public void shoot()
    {
        player.transform.localPosition = new Vector3(1 * size / 10, 1 * size / 10, 1 * size / 10);
        GameObject projectile = Instantiate(ball, player.position, cam.rotation);
        projectile.transform.localScale *= size / 10;
        Rigidbody ballrb = projectile.AddComponent<Rigidbody>();
        ballrb.useGravity = false;
        ballrb.AddForce(cam.rotation * Vector3.fwd * speed, ForceMode.Force);

    }
}

But however after i instantiate the cannonballs from the cannon, I cant get it to instantiate an explosion as well as being unable to access the explosion gameobject and change its properties. I spent a few hours trying to solve this but all the resources i found did not mention anything about instantiating from a prefab so pls help.

this for projectile

this for cannon

this is whats going on so far

1

There are 1 answers

2
Valera Kvip On
  1. check if life > 0
  2. check if Awake occurs
private void Awake()
{
    Debug.Log("Awake");
 }
  1. check if OnCollisionEnter occurs
 void OnCollisionEnter(Collision collision)
 {
      Debug.Log("OnCollisionEnter");
 }
  1. Check if the explosion and cannonball are initialized - it's not obvious where they came from!
  2. Check out Console for errors

That's enough to find the problem and fix it, or ask a good question.