Can't change GameObject color via script?
Here is your problem:
new Color(0f, 0f, 0f, **255f**);
The Color
constructor parameter takes values from 0f
to 1f
but you are passing 0f
to 255f
range value to it.
That should be:
colorToFadeTo = new Color(0f, 0f, 0f, 1f);
If you want to use the 0
to 255
range then you must divide it by 255
.
colorToFadeTo = new Color(0f, 0f, 0f, 255f/255f);
Also, there is Color32
which can take values between 0
and 255
. You can use that then covert it back to color.
Color32 color32 = new Color32(0f, 0f, 0f, 255f));
Color color = color32;
Can't change color of the material, Unity
Are you sure the method is being called? OnCollisionEnter
is triggered when this collider/rigidbody has started contact with another rigidbody/collider.
Check that there is a collider/rigidbody on the object that the sphere collides with and on the sphere itself
Also, try using Debug.Log()
to make sure that the code is triggered.
I checked your line in the Start() method, it works. The problem is something else
Change prefab color from script
You must change the start color of the ParticleSystem
, not the material of an nonexistent MeshRenderer
.
newSmoke.GetComponent<ParticleSystem>().startColor = Color.red ;
https://docs.unity3d.com/ScriptReference/ParticleSystem-startColor.html
Change Color of just one instantiated object in Unity
Make sure you are refencing the instantiated Object instead of the prefab.
This should work for you:
GameObject instance = Instantiate(prefab);
instance.GetComponent<Renderer>().material.color =
new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f),1f);
When changing the colour of a prefab using a c#script, it shows in the inspector but not in the game view
Finally found it after days of searching!
Thanks to https://stackoverflow.com/a/54008057/11829883
Because the arrows body was a child of the arrow model which was a child of the actual arrow prefab, I had to call GetChild(0)
twice on the object - for some reason GetComponentInChildren
wasn't working so i assumed that wasn't the issue
This is the line of code that fixed it:
new_c.transform.GetChild(0).GetChild(0).GetComponent<MeshRenderer>().material.color = Color.yellow;
Related Topics
How to Use Default Serialization in a Custom System.Text.JSON JSONconverter
Is There Any JSON Web Token (Jwt) Example in C#
Sending Outlook Meeting Requests Without Outlook
Send Keys Through Sendinput in User32.Dll
How to Include Line Numbers in a Stack Trace Without a Pdb
Entity Framework 6 Code First Custom Functions
.Net and Bitmap Not Automatically Disposed by Gc When There Is No Memory Left
String.Isnullorempty(String) VS. String.Isnullorwhitespace(String)
How to Generate a Constructor from Class Fields Using Visual Studio (And/Or Resharper)
What's a Good Threadsafe Singleton Generic Template Pattern in C#
Why Is It Impossible to Override a Getter-Only Property and Add a Setter
Possible to Use Automapper to Map One Object to List of Objects