Casting a spell towards target

Hi i was wondering how i would go about fixing my particle spawning for my project currently im wanting to use this as a magic spell cast that spawns on enemy’s position but currently im running into an issue where when i call this on my combat script it does not work as it cant reference the particle since its calling this from another script how could i fix this? i’ve posted my magic script code below and the code i am calling on my combat script.

Error:
NullReferenceException: Object reference not set to an instance of an object

What im calling on combat script

public MagicManager magic;
magic.castSpell();

Magic script class

using UnityEngine;
using System.Collections;

public class MagicManager : MonoBehaviour {

    #region Hide
    [HideInInspector]
    public PlayerController playerControl;
    public Camera playerCam;
    public delegate void UpdateOwnerCamera(Camera owner);
    #endregion

    [Header("Spell")]
    public ParticleSystem spell;

    void UpdateCameraEventHandler(Camera owner)
    {
        playerCam = owner;
    }

    public void castSpell()
    {
        Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 20f))
        {
            if (hit.collider.gameObject == gameObject)
            {
                if (hit.transform.tag == "Enemy")
                {
                    Instantiate(spell, hit.transform.position, Quaternion.identity);
                }
            }
        }
    }
}

In your combat script you need something like this:

public class <combat script> {
   public MagicManager magic;

   void Start() {
      // If the combat script and magic script are on different game objects then do the following:
      magic = GameObject.Find("<gameobject name that has the MagicManager>").GetComponent<MagicManager>();
      // else (means they are on the same gameobject)
      magic = gameObject.GetComponent<MagicManager>();
   }

   public void doSomething() {
      magic.castSpell();
   }
}

Change the things with < > wrapped around them. You need to enter the values. Then you need to pick one of the ‘magic = blah blah blah’ statements depending on the situation

1 Like