I am in the Mod The Cube and I am trying to get a random color for it when it moves position

I am getting an error when I use the Random.Range method for colors and I keep getting a Serialization warning but I am not sure what I am doing wrong. Can someone point me in the right direction please?

public float red = Random.Range(0, 255);
public float green = Random.Range(0, 255);
public float blue = Random.Range(0, 255);
public float alpha = 2;

Any help would be awesome
Rin

Randon.Range shouldn’t be used in an inline-initializer like that. Been a while since I did the old Mod the Cube lesson, but I imagine you can generate these colours in the Update loop that is moving this cube as well.

1 Like

@Rinlore @spiney199 This is correct! You want this in your Update loop or in an area where this code will be looped over time because it will only be set once the way the values are initialized in the screenshot. Hope that helps!

1 Like

@unityCM_Kirk and @spiney199
Ok I have tried to place them in the update function and it gets worse for the errors. I know that I am just missing something but I am not sure what. With teaching myself to code I know that there are some areas that I am not good at or just don’t know yet.

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

public class Cube : MonoBehaviour
{
    public MeshRenderer Renderer;
    public float cubeMoveTime = 1.5f;
    public float cubeStartPoint = 0;
   
    public new Renderer renderer;

    void Start()
    {
        transform.position = new Vector3(3, 4, 3);
        transform.localScale = Vector3.one * 1.3f;


        //InvokeRepeating("ChangeColor", 1f, 1f);
        Material material = Renderer.material;
    }
    
    void Update()
    {
       
        transform.Rotate(10.0f * Time.deltaTime, 10.0f * Time.deltaTime, 10.0f * Time.deltaTime);

        public float red = Random.Range(0f, 1f);
        public float green = Random.Range(0f, 1f);
        public float blue = Random.Range(0f, 1f);
        public float alpha = Random.Range(0f, 1f);
        

        if (Time.time > cubeStartPoint)
        {
            
            cubeStartPoint = cubeMoveTime + Time.time;
            transform.position = new Vector3(Random.Range(4, 0), Random.Range(7, 2), Random.Range(10, -10));
            material.color = new Color(red, green, blue, alpha);


        }
    }
    
}

Thanks
Rin

When declaring variables in a method you don’t declare accessibility modifiers (public, private, etc).

In this case you can just remove the public accessibility modifiers from the four floats you’re generating in Update.

@spiney199 @UnityCM_Kirk
I know that I was missing something and it would be simple. That fixed the whole thing. It now does exactly what I wanted it to. I have been working on it for two days and trying different things. Thanks for that. This is also one of the first sights that have answered my question in like 20 minutes. Once I could get back at it today.

Rin

1 Like

And since you’re learning… notice that you don’t use the 4 color values if the test above does not pass. This means you should fetch the random colors inside that test as well. AND… you don’t actually need to get 4 individual random values but could substitute a method (you wrote) that returns a random Color. And another that returns a random Vector3

@tleylan

I will have to work on that tomorrow.

using UnityEngine;

public class Cube : MonoBehaviour
{
public MeshRenderer Renderer;
public float cubeMoveTime = 1.5f;
private float cubeStartPoint = 0f;
private Material material;

void Start()
{
    transform.position = new Vector3(3, 4, 3);
    transform.localScale = Vector3.one * 1.3f;

    if (Renderer != null)
    {
        material = Renderer.material;
    }
    else
    {
        Debug.LogError("MeshRenderer reference is missing!");
    }
}

void Update()
{
    transform.Rotate(10.0f * Time.deltaTime, 10.0f * Time.deltaTime, 10.0f * Time.deltaTime);

    if (Time.time > cubeStartPoint)
    {
        cubeStartPoint = Time.time + cubeMoveTime;
        transform.position = new Vector3(
            Random.Range(0, 4),
            Random.Range(2, 7),
            Random.Range(-10, 10)
        );

        if (material != null)
        {
            float red = Random.Range(0f, 1f);
            float green = Random.Range(0f, 1f);
            float blue = Random.Range(0f, 1f);
            float alpha = Random.Range(0.5f, 1f);
            material.color = new Color(red, green, blue, alpha);
        }
    }
}

}
TRY THIS ONE

1 Like

I don’t know if the OP is interested but I enjoy discussions like this as (I think) it can get developers to “twist the code” in their head a bit. This lets them see variations on a theme and should help them choose a system they like.

I’d recommend against the habit of checking for things like Renderer is null. It certainly shouldn’t recover from such an event. The concept of “fail fast” is useful here. May as well stop the app and get it fixed because while there may be no error it will not operate as designed. When working properly material will never be null so checking it won’t matter.

2 Likes

@tleylan @ pradeepyadavkkte @spiney199

I know that there are some holes in the knowledge but living where I do and having some serious social anxiety I have had a hard time connecting with anyone or more they are not willing to help. I have tried to ask questions but getting an answer on discord or the like can make it difficult to find if someone replied unless they message you. I have tried forums like this before but this is the first time people did not make me feel like I am asking stupid questions. I know that have holes in my understanding of coding and building with it. Also you have all put more input into this than anyone ever has. I also know that it is a lack of experience but that will only come with time and the more that I do. I have also fighting my brain since I have been diagnosed with dyslexia and some things get mixed up in my head. I have been working for years to reprogram my head and the fact that I am making progress with it is nice. I write and type a lot in doing this. This is all in just to say thinks because you have helped keep the hope that one day I can do better for myself and my family. Any help with learning this is always welcome. I wont ever work on my feet again but my brain works just fine for the most part.

I’ll suggest that you come up with your own list of dozens of little “puzzles” to solve and work out strategies for each one. Moving and scaling objects are fundamental. Changing colors, changing text, playing sounds, getting input from keyboard or controllers, etc. You don’t need to write a game to make the parts of a game and making reusable parts will help you complete games.

Try to solve your issues and then post questions here. Particularly describe what you are trying to do and what you’ve tried so far. Unless it is “I’m getting a null reference error” in which case trust the tools and just find the null reference :slight_smile:

Good luck.

1 Like

@tleylan

Decided to try out your idea with the methods and I have hit a wall in what I am doing wrong. I know that it is simple but I am not sure.

static void RandomColor()
{
    float randColor;
    float red = Random.Range(0f, 1f);
    float green = Random.Range(0f, 1f);
    float blue = Random.Range(0f, 1f);
    float alpha = Random.Range(0.5f, 1f);
    
    randColor = new Color(red, green, blue, alpha);
   return randColor;
}

I am thinking it is in the static void part but I am not sure. I know that to call it in the if statement I just need to call it like RandomColor(). Like I said holes in my learning. I think that it is simple but I am not sure.

There are going to be lots of walls and design decisions along the way. Your first problem here is that you have declared the method as returning a void and you are trying to return a Color.

I recommend always explicitly declaring scope so public static or private static depending upon your use case. That said you can create a static class full of helper methods for the time-being and refactor if that becomes too complex and you end up with the following to give yourself a base.

using UERandom = UnityEngine.Random;

public static class Helpers
{
}

I alias the Random method because it is ambiguous (.Net has one). You can declare a static property and it should be available via the static class.

public static class Helpers
{
	public static Color RandomColor => new Color(UERandom.Range(0f, 1f), UERandom.Range(0f, 1f), UERandom.Range(0f, 1f), UERandom.Range(0.5f, 1f));
}
	material.color = Helpers.RandomColor;

RandomColor has repeated logic so I tend to break it out. It makes it testable and modifiable if for instance one color needs to be treated differently. And you get the following:

public static class Helpers
{
	public static Color RandomColor => new Color(RandomRed, RandomGreen, RandomBlue, RandomAlpha);

	public static Single RandomColorValue => UERandom.Range(0f, 1f);

	public static Single RandomRed => RandomColorValue;
	public static Single RandomGreen => RandomColorValue;
	public static Single RandomBlue => RandomColorValue;

	public static Single RandomAlpha => UERandom.Range(0.5f, 1f);
}

I use the .Net type definitions (I believe most C# developers do not) but I like the syntax highlighting and the types map across all .Net languages. So modify them if you want or try it for awhile and see how it feels to you.

Notice how there is little need for comments as the properties are self-evident. Again rather than Helpers you can name the class something more expressive if you like.

If the properties needed a parameter value you would clearly opt for static methods but at the moment we don’t need them.

Oh, quick note. Since we have a static class that has static properties there is nothing that prevents this from being used outside of your Cube class or Update method. You can test them with simple console.log statements, etc.

@tleylan
Ok I am not sure what I am doing wrong. The end of the Mod The Cube project is to create a WebGL to show it off. Now my problem. When I try to do that under the build screen my program breaks. I am not sure why. I also can not build until I do that until I convert it which makes since but I don’t know why once that is done it breaks. Now it very well might be the computer I am using. I am on a rather old system since it was all I can afford to get. Any ideas on what might be causing this to happen.

Thanks

I don’t know about Mode The Cube :slight_smile: I’d bet money that it isn’t your computer unless it is running CP/M. You can check to see if you can run any WebGL example you can find to test your particular browser.

In the future terms like “it breaks” provides no information. If you get errors you should list at least a few of them. I’d check the instructions you’re following one more time to see if you could have missed something.

@tleylan

That is just it. There were no errors but when I went to hit play it nothing happened and it was like the code was not even there. I exited with out saving and went back in and it worked just fine. Then when I tried to switch back to windows platform it said that it could not do that when it was still being used in another one. When I looked for WebGL on the 6 version I could not find it and then I tried to install it I get:
[Package Manager Window] Error adding package: com.unity.connect.share@4.2.3.
EINVAL: invalid argument, futime
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

These are all I have to work with so for me it broke. I am still trying to figure out if I have to use the assets sight to get the WebGL I did fide something there but I am not sure if it is the right thing. I am also updating what I find that needs it.

Thanks

@tleylan

I am not sure what is wrong. When I use Unity 2022 the code will not work but I can find the WebGL option. Then when I try in 6 then I can’t download it and I get the above error. I am really starting to think it is the computer since it is almost 10 years from what I can tell and is not upgradable to windows 11. I have had this problem before and when updating things did nothing to help I am guessing I am just not going to be able to upload this project or others until I have something that is more compatible with what I want to do. That might take some time but one day I am going to get there.

[Package Manager Window] Error adding package: com.unity.connect.share@4.2.3.
EINVAL: invalid argument, futime
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

Thanks

1 Like