Hi,
I’m have a ton of trouble successfully calling this function. I believe I have it set up right, and my code matches other ‘solutions’ I’ve found already. Everything compiles, but Unity doesn’t call the function, and gives me this error:
I have made sure that the CameraShake script is attached to the MainCamera in the scene (only camera in the scene.)
This is my code:
As you can see, the “test shake” prints, but the error happens when it tries to call that next line.
Also, I tried declaring it like this, which had the same outcome:
CameraShake shake = this.gameObject.GetComponent();
Any insight would be greatly appreciated.
Hi
You don’t set the ‘shake’ variable anywhere.
As a result, it is ‘null’ (i.e. not set), and you are getting a ‘null reference exception’ - this is the scripts way of telling you that you are are trying to reference an object that is null.
Assuming CameraShake is a component of the same object as Brick, you could add the line:
shake = gameObject.GetComponent<CameraShake>();
to the Start function.
Note that this must be done int he Start function - not as part of the variable definition. If you place it in the variable definition, it is executed when your component is first created in memory, and there is no guarantee anything else has been created at that time!
If this doesn’t work, then your brick object probably doesn’t have a camera shake component attached.
p.s. in future always post code using the code formatting option in the help forums - see the little 101010 icon in the text editor!
-Chris
I found that if I manually add a NewScript > CameraShake, the code works. I deleted “public” in front of CameraShake shake; when I declared it, so that the brick was no longer asking for it to be attached. In any case, I have my answer now.
Thank you!