How to render a constructor-created gameObject
Hello Community,
Quick noob question here. My plan was to quickly create a game object via script using the new GameObject() constructor. My motivation for using the constructor instead of instantiating a prefab, is because of the game object being simplistic, only to be visible and have a transform. I didn't want to create a prefab and add a public/serialized variable to the script for dropping in the prefab. But after creating the game object with the code below, it turns out the object (a supposed sphere) remains 'invisible'. How do i make the object visible in the scene? Here's the code, and thank you for reading.
GameObject blueSphere;
viod Update()
{
if (blueSphere == null)
{
blueSphere = new GameObject("BlueBall");
blueSphere.transform.position = Vector3.zero;
blueSphere.transform.localScale = Vector3.one;
blueSphere.AddComponent<MeshRenderer>();
blueSphere.GetComponent<MeshRenderer>().enabled = true;
blueSphere.GetComponent<MeshRenderer>().material.color = Color.cyan;
}
}
Answer by Hellium · Sep 20, 2018 at 10:47 AM
If you read your code :
You create an empty
You set its position and scale
You add a MeshRenderer and apply a color
But even if you add a MeshRenderer, you never tell what mesh to render.
In your case, if you just want a Sphere, use the GameObject.CreatePrimitive
function:
if (blueSphere == null)
{
blueSphere = CreateSphere( "BlueBall", Vector3.zero, Vector3.zero, Vector3.one, Color.cyan );
}
// ...
private GameObject CreateSphere( string name, Vector3 position, Vector3 rotation, Vector3 scale, Color color )
{
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere
sphere.name = name ;
sphere.transform.SetPositionAndRotation( position, Quaternion.Euler( rotation ) );
sphere.transform.localScale = scale ;
sphere.GetComponent<MeshRenderer>().material.color = color;
Component.Destroy( sphere.GetComponent<Collider>() ) ; // If you don't want the collider automatically attached
return sphere ;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612174947im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Renderer.isVisible returning true with back side of Quad Primitive 0 Answers
Issue where Fading out Game Object causes screen to blank and then reload with gameobject gone 0 Answers
Material disappears after LoadScene 1 Answer
material.SetColor causing Hidden/InternalErrorShader 1 Answer
Rotating and lerping to another material with custom shader. 0 Answers