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;
    }
}

If you read your code :

  1. You create an empty
  2. You set its position and scale
  3. 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 ;
}