Hello,
I’m a total newbie, trying to make a character summon an object, and for that object to follow mouse cursor position when the mouse button is pressed, but while the muse button is pressed i get a continuous error “NullReferenceexception: object reference not set to an instance of an object”
This is my script for the character:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
Rigidbody2D rigbody;
public GameObject FlamePrefab;
public Transform nenflameObj;
float horizontal;
float vertical;
public float runSpeed = 5.0f;
// Start is called before the first frame update
void Start()
{
rigbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
public void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(KeyCode.C))
{
Instantiate();
}
}
public void Instantiate()
{
GameObject nenflameObj = Instantiate(FlamePrefab);
}
private void FixedUpdate()
{
rigbody.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}
}
And this is the script for the object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NenFlame : MonoBehaviour
{
private Vector3 mousePosition;
private Rigidbody2D rb;
private Vector2 direction;
private float moveSpeed = 100f;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
public void Update()
{
if (Input.GetMouseButton(0))
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = (mousePosition - transform.position).normalized;
rb.velocity = new Vector2(direction.x * moveSpeed, direction.y * moveSpeed);
}
else
{
rb.velocity = Vector2.zero;
}
}
}
I got stuck on this for a while.
Thanks in advance