using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Buyu : MonoBehaviour
{
public Transform buyuNesnesi; //Büyü yapmamıza yarar.
public Transform hedef;
void Awake()
{
hedef = GetComponent<Transform>();
}
public void atesle()
{
if (buyuNesnesi != null)
{
Vector3 yonel = (hedef.position - transform.position);
Transform vur = Instantiate(buyuNesnesi, transform.position, Quaternion.identity) as Transform; //Tip uyuşmazlığı olmasın diye.
vur.transform.parent.GetComponent<Transform>().GetComponent<Rigidbody2D>().velocity = yonel * 10f * Time.deltaTime;//Hangi hızla yollanacak.
Quaternion gidisat = Quaternion.Lerp(transform.rotation, hedef.rotation, 10f + Time.deltaTime);
vur.rotation = Quaternion.RotateTowards(transform.rotation, gidisat, 30f * Time.deltaTime);
vur.position = Vector3.MoveTowards(vur.position, hedef.position, 20f * Time.deltaTime);
Destroy(vur.gameObject, 5f);
}
}
void OnTriggerEnter2D(Collider2D carpisan)
{
if(carpisan.gameObject.tag=="Player")
{
Debug.Log("Vurduk");
atesle();
}
}
}
NullReferenceException: Object reference not set to an instance of an object
Buyu.atesle () (at Assets/Buyu.cs:24)
Buyu.OnTriggerEnter2D (UnityEngine.Collider2D carpisan) (at Assets/Buyu.cs:36)
You can tell from the backtrace that the exception occurs on on line 24 of the script. Unfortunately, the exception doesn’t tell us what on this line is null.
Assuming line 24 in the original script is the same as in the code you’ve posted, there are a few possibilities:
parent could be null (actually likely, objects are instantiate at the root, therefore don’t have a parent and you don’t set its parent before this line)
GetComponent<Transform>() is actually redundant. parent already is a Transform and so the GetComponent returns the same object, you can just remove this.
GetComponent<Rigidbody2D>() could be null if the parent doesn’t have a Rigidbody2D component.
Put a series of Debug.Log statements before this line and log out all the return values to see what exactly is null. Alternatively, use a debugger and break at that line, then you can inspect and step through the code to see where exactly the exception occurs.
I do hope Unity/.Net will at some point improve the stacktrace to include column numbers, which will make it much easier to tell what is null.
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.