- Home /
"Object reference not set to an instance of an object" error
First and foremost here are the 2 scripts that i'm trying to make interact: Disregard variable initialization and "ThrowObject" method in the second script. Just there to add some context.
FIRST:
using UnityEngine;
using System.Collections;
public class playerSounds : MonoBehaviour {
public AudioClip step;
public AudioClip punch;
public AudioClip collision;
public AudioClip fire;
void Start () {
}
void Update () {
}
public void PlayClip(AudioClip clip){
audio.clip = clip;
audio.Play();
}
}
SECOND:
using UnityEngine;
using System.Collections;
public class shootCrate : MonoBehaviour {
public GameObject projectile;
public GameObject referenceObj;
public float addForceX = 0;
public float addForceY = 250;
public float addForceZ = 750;
public float fireRate = 0.5F;
public float nextFire = 0.0F;
public float fireUp = 3; // spawn point distance up from the head
public float dist = 2; // spawn point distance from the turret
void Start () {
}
void Update () {
playerSounds pSounds = GetComponent<playerSounds>();
if ( Input.GetButton("Fire1") && Time.time > nextFire)
{
// Debug.Log("A key or mouse click has been detected");
nextFire = Time.time + fireRate;
ThrowObject();
pSounds.PlayClip(pSounds.fire);
}
}
void ThrowObject () {
Vector3 projPos;
projPos = new Vector3( transform.position.x,transform.position.y, transform.position.z );
projPos.y += fireUp;
GameObject crateClone = Instantiate(projectile, projPos, referenceObj.transform.rotation) as GameObject;
// Debug.Log("projectile created <"+projRot+">");
crateClone.rigidbody.useGravity = true;
}
}
So, when i actually try to run this i get the error mentioned in the title, that points to line 33 of the second method, which is the "pSounds.PlayClip(pSounds.fire);" bit in the Update(). Any ideas to why this is happening?
Thanks in advance.
Pedro
Answer by trs9556 · Jun 16, 2013 at 03:29 AM
pSounds is null, or more specifically not set to an instance of an object.
Is the playerSounds script attached to the same gameobject that your shootCrate is attached to?
not really. The playerSounds script is attached to the first person controller whereas the shootCrate is attached to an object within the first person controller.
Your answer
![](https://koobas.hobune.stream/wayback/20220613104248im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object reference not set to an instance of an object 1 Answer
Object Reference not set to an Instance 2 Answers
NullReferenceException:"Object reference not set to an instance object" 1 Answer
Script decides not to run anymore 1 Answer
i don't understand "NullReferenceException: Object reference not set to an instance of an objec" 0 Answers