Generating objects

Hello everyone, first time here, and mainly just experimenting and messing around in Unity to pass some time, I’m honestly having a blast so far. Let me preface this by saying im a beginner and by no means have a single clue what I got myself into lol. I’ve been using ChatGPT (talking AI) for those that don’t know it can help out with creating code, granted sometimes it works, and other times it breaks and without it I wouldn’t have gotten as far as I did.

So my question is, I’m trying to generate Stars (which i created with this amazing tutorial here:

) based on the camera being the generator. The AI recommended that i use Chunks to load more stars once the camera enters said chunk and i can tinker with those values (adding a screen shot for that:
So the issue I ran into and can’t seem to figure out even with the help of that AI is that once I leave the starting area the stars that generate at the start will despawn once I leave that chunk but after that nothing happens, my main sphere which contains the script and the shader/material is the only thing that will remain in the scene. Im going to put my code below and as a file, and mind you I’m clueless, all of that was generated by the AI, I’m not expecting to have my handheld im just curious and very interested in what everyone thinks and if there is a possible solution to this. Thanks! :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StarGenerator : MonoBehaviour
{
    public Material starMaterial;
    public Shader starShader;
    public int starCountPerChunk = 10;
    public float minStarSpacing = 1.5f;
    public float minStarSize = 0.5f;
    public float maxStarSize = 1.5f;
    public float maxViewDistance = 100.0f;
    public float chunkDistance = 50.0f;

    private List<GameObject> stars = new List<GameObject>();
    private Vector3 lastChunkPosition;

    void Start()
    {
        // Generate the first chunk of stars at the start position
        lastChunkPosition = transform.position;
        GenerateStars();
    }

    void Update()
    {
        float cameraDistance = Vector3.Distance(Camera.main.transform.position,                       transform.position);

        // Check if the camera has moved to a new chunk of stars
        if (cameraDistance > chunkDistance && Vector3.Distance(lastChunkPosition, transform.position) > chunkDistance)
        {
            lastChunkPosition = transform.position;
            GenerateStars();
        }

        // Despawn stars that are beyond maxViewDistance from the camera
        if (stars.Count > 0)
        {
            for (int i = stars.Count - 1; i >= 0; i--)
            {
                if (Vector3.Distance(Camera.main.transform.position, stars[i].transform.position) > maxViewDistance)
                {
                    Destroy(stars[i]);
                    stars.RemoveAt(i);
                }
            }
        }
    }

    private void GenerateStars()
    {
        // Create a new game object for each star in the chunk
        for (int i = 0; i < starCountPerChunk; i++)
        {
            // Create a new star game object with a sphere mesh and material
            GameObject star = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            star.name = "Star";
            star.GetComponent<Renderer>().material = starMaterial;
            star.GetComponent<Renderer>().material.shader = starShader;

            // Randomly position the star within a grid
            Vector3 randomPosition = GenerateRandomPosition();
            while (IsPositionTooCloseToExistingStars(randomPosition))
            {
                randomPosition = GenerateRandomPosition();
            }
            star.transform.position = randomPosition;

            // Set the scale of the star to a random size
            float scale = Random.Range(minStarSize, maxStarSize);
            star.transform.localScale = new Vector3(scale, scale, scale);

            // Randomly change the BaseColor and CellColor of the star material
            Color baseColor = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
            Color cellColor = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
            star.GetComponent<Renderer>().material.SetColor("_BaseColor", baseColor);
            star.GetComponent<Renderer>().material.SetColor("_CellColor", cellColor);

            // Add the star to the list of stars
            stars.Add(star);
        }
    }

    private Vector3 GenerateRandomPosition()
    {
        // Generate a random position within a box around the center of the generator
        float x = Random.Range(-minStarSpacing, minStarSpacing) + Camera.main.transform.position.x;
        float y = Random.Range(-minStarSpacing, minStarSpacing) + Camera.main.transform.position.y;
        float z = Random.Range(-minStarSpacing, minStarSpacing) + Camera.main.transform.position.z;
        return new Vector3(x, y, z);
    }

    private bool IsPositionTooCloseToExistingStars(Vector3 position)
{
    // Check if the position is too close to any existing stars
    foreach (GameObject star in stars)
    {
        if (Vector3.Distance(position, star.transform.position) < minStarSpacing)
        {
            return true;
        }
    }
   
    return false;
}
}

8933166–1224729–StarGenerator.cs (3.98 KB)

The AI doesn’t relieve you of the responsibility of learning what you’re actually doing.

At a minimum you should be able to describe what each line does above.

There’s no excuse since 100% of the language is publicly documented and explained in tutorials.

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.