As I beginning to dissect a project template from the asset store. There’s a game object, the ‘Player’, that has a script component called Cs Player Attack. It’s a C# script called csPlayerAttack. I manage to attach the same script in, but as you can see from the image below, their properties don’t seem to share the same values.
I know that I can copy paste the value from one to another, but I’m looking to understand how this was done. As I click the ‘Select Game Object’ little circle button at the far right hand side, the selection window pop up but there’s no where the objects such as, bulletSpawnPoint, PlayerWeaponA…
So my question is, this normal? Or is there a way I can hook this value up? Appreciate the explanation very much.
When you add a behaviour to an object you are creating a new instance of the behaviour or class defined inside. I dont know how much Object Oriented programming you’ve done so basicly:
A class defines an object.
When you add a script to a GameObject
it gains it’s own ‘object’ or
instance of that class.
If you define a method or variable as
static, it will be the same across
all components as you are thinking.
Hope that clears things up somewhat
Also, as a handy thing to know, if you press the cog in the corner of the component inspector view you can copy and paste them with their values.
Attaching a component creates a new instance of that component on the object. The reason that your new instance’s object references aren’t the same is because you can’t initialize reference fields in a script with default values, you have to assign them through the inspector.
What you are looking at is most likely a prefab that has had its references assigned to child objects of a prefab (which don’t show up in the ‘Select GameObject’ picker). You’d have to expand the parent prefab and drag in the desired reference to your field to assign it.
Unfortunately, for some unfathomable reason, Unity will only show you the 1st level children of a prefab hierarchy. So say that ‘PlayerWeaponA’ is a 2nd or 3rd child of ‘Player’ - to assign it to your ‘Player Weapon A’ field, you’d have to create an instance of it in the scene (drag prefab onto scene), which would give you access to the full hierarchy, expand the player object to expose the ‘PlayerWeaponA’ child, and click and drag it to your ‘Player Weapon A’ field. Then you can apply the changes of the prefab instance onto the prefab itself (clicking ‘Apply’ in the Prefab section underneath the object’s name) and can delete the instance from the scene.