- Home /
Not understanding GetComponent with prefabs
I copied a project and it creates players using:
player = ((GameObject)Instantiate(UserPlayerPrefab, vector, quat))
.GetComponent<UserPlayer>();
UserPlayer
is a script. This works, but I don't understand the association between the script (filename is UserPlayer
) and the actual game object. The project has prefab/UserPlayer
which is a prefab that has a capsule mesh. I wanted to use a more complex character design, so I imported an fbx file, created a prefab from it, and added the UserPlayer
script as a component. I renamed the original UserPlayerx
and the new one to UserPlayer
.
However, when I run the game, when the player
is created, it's still using the UserPlayerx
prefab (i.e. drawing a capsule). There doesn't seem to be any association between the UserPlayer
script and the prefab except that the script is a component of the prefab, but the script is also a component of my new user player, so I'm at a complete loss.
How can I create a component using the new prefab?
In Unity, when you rename a prefab, the editor will help you out by fixing the references to that prefab in your other scene game objects. I suspect that happened here. Go to whereever you set UserPlayerPrefab in the editor and choose the new prefab.
Answer by hd27 · Dec 10, 2013 at 06:17 PM
Try removing the UserPlayer script from the prefabs and adding it to the Instantiated gameobject; What I mean is:
GameObject player = (GameObject)Instantiate(UserPlayerPrefab, vector, quat);
UserPlayer userPlayer = player.AddComponent<UserPlayer>();
This will create a new gameobject in the scene from the prefab and then it will add the UserPlayer component to it and will store the component in a variable so you can access it;
I hope this is what you wanted to do.
Unfortunately this has the same effect. It still makes a clone of UserPlayerx
ins$$anonymous$$d of UserPlayer
.
I figured it out. The UserPlayerPrefab
was set in the inspector. I had to update it to use the new prefab.
Answer by guitarxe · Dec 10, 2013 at 07:04 PM
From a similar question I asked here, it looks like you cannot link anything external to the prefab. Thus you could try adding your scripts to an instantiated object from your prefab after you have instantiated it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123852im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Acces a component on an instantiated object 1 Answer
cant add script 1 Answer
NullReferenceException from a script after linking prefab with drag and drop in inspector. WTF? 1 Answer
Controlling Animator through Script. I'm stuck please help! 0 Answers