- Home /
AddComponent in script modifying Prefab Assets?
I've got some weird behavior going on in my code and I'd like to know what's causing it. Here's the setup:
There's a Brick prefab. There's a Pool prefab that's supposed to be an instance factory/pool. This Pool prefab has a monobehaviour with an empty GameObject variable for the GameObject that it's supposed to replicate.
I create a scene instance of the Pool in the scene and call it BrickPool. The BrickPool scene instance has it's Prefab variable set to the Brick Prefab from my Assets.
At runtime, the pool uses AddComponent to append a Poolable Component (with a Return method) onto whatever Prefab it's supposed to pool, then instantiates 20 of that Prefab in the scene.
Here's the weird behavior: Each time I run the program (not each time a Brick is pooled), a duplicate Poolable component gets added to my Brick class. If I run the program 4 times, Poolable gets added as a component to the Brick Prefab asset and remains there, even if the game isn't running.
What am I doing wrong?
Here's the relevant stuff from the Pool class:
public var Prefab : GameObject;
public var Size = 20;
private var _pool : GameObject[];
function Start() {
_pool = new GameObject[Size];
Prefab.AddComponent(Poolable);
for (var i = 0; i < Size; i++) {
var go = Instantiate(Prefab, Vector3.zero, Quaternion.identity);
_pool[i] = go;
}
}
I'm not sure how to illustrate the Unity editor assets and scene instances other than to take copious screenshots, but I'll do so if it provides the necessary information to describe what's happening.
It sounds like adding a component to a prefab changes that prefab permanently. Why don't you just try removing the component in OnApplicationQuit(){}. That would get rid of it any time you stop your project.
It's ultimately not going to impact development. It's more of a question I'm asking from the perspective of being a Unity $$anonymous$$cher for middle school students, and also from a runtime memory/efficiency perspective.
If I package the application, it's probably not going to be re-writing the Prefab inside the package. If it modifies it in Unity Editor, I don't have to save any changes made. (The changes don't appear when I reload the scene.) I could also stick in code that checks for the component before adding it.
I don't see why you want to add the component during run time in the first place.
Your answer
Follow this Question
Related Questions
Adding prefab ParticleSystem to a GameObject? 0 Answers
prefab as AddComponent? 1 Answer
pooled prefab missing child 1 Answer
(Similar Prefabs) vs (Single Prefab + AddComponent) 2 Answers