- Home /
how can I change the gameobject at runtime?
How do I change gameobject at runtime? For example, I picked up a power up and the bullets should changed to powerBullets. Example:
var bullet : GameObject;
function Update()
{
if(powerUp==true)
{
bullet = powerBullets;
}
else
{
bullet = normalBullets;
}
}
Answer by Piflik · Jan 10, 2013 at 04:57 PM
Depends on how your code looks like. If you want to instantiate different objects, simply add another gameObject variable to your script and put the other bullet prefab in there, then choose the one to instantiate based on if you have picked up the upgrade, or not.
If you want to change simple properties after you spawned a bullet (size, color, etc), save the instantiated object in a temporary variable and you have access to all its public properties.
But to help you further, you'd have to update your question with your code and details to what you actually want to do. 'Change to power bullets' is too unspecific.
Answer by robertbu · Jan 10, 2013 at 05:48 PM
There are many ways to change the look of a bullet and there are tradeoffs with each. The easiest might be to just change the texture. For most shaders you can do something like:
renderer.material.mainTexture = texPowerBullets;
The texture can either be linked directly into a public variable or dynamically loaded from Recources using Resources.Load()
.
Another possibility is to have an empty parent game object with a public variable to two children game object. One game object is the normal bullets, one is the power bullets. Then you can do something like:
goNormalBullets.renderer.enabled = false;
goPowerBullets.renderer.enabled = true;
Another possiblity is swap out the mesh. Assuming you had a public variable that was linked to a mesh for your power bullets:
MeshFilter meshfilter = GetComponent<MeshFilter>();
meshfilter.mesh = meshPower;
Your answer
![](https://koobas.hobune.stream/wayback/20220613090727im_/https://answers.unity.com/themes/thub/images/avi.jpg)