Set material color with unity C# - c#

I am working on a game in UNITY. For this game so far I have 3 cubes that I wish to target. I have them set up in an array and when I hit tab the targets switch between them based on distance. This is all fine but I have run into a pickle and it is that I wish to have the cubes I target turn red for visual representation. I seen on Youtube that people used the following line of code :
selectedTarget.renderer.material.color = Color.red;
However this does not work for me. I then seen a comment saying :
The function to render was deprecated. Below should work...
selectedTarget.GetComponent<Renderer>().material.color = Color.red;
This code does not work for me either. I get no errors mind you, it runs fine but the cubes do not turn red. Has anyone any idea on whether or not I am doing this right? I will post the entire script below and the code I am on about is in selectedTarget(). Any help would be appreciated and thank you!
private void SelectTarget(){
selectedTarget.renderer.material.color = Color.red;
}

I had the very very very same problem. I had no errors. You need to be able to set the color property on the material, and only CERTAIN shaders have this color property. I had to use for example Self-Illuminated/Bumped instead of say Mobile/VertexLit. Then changing the color should be fine as you can see a Main Color property in the editor/inspector.
Also make sure your mesh has Materials. If you don't have Materials, even if it's blank or a placeholder else it won't work! I'd create a texture preferably white colored and small like 5x5. Then attach the texture to your cube. After you attach it you can color it!
I've done cool stuff in my game with Color.Lerp, it'll fade from one color to the next! This example below ping pongs from white to red when the player is hit by an enemy indicating damage!
transform.renderer.material.color = Color.Lerp(Color.white, Color.red, Mathf.PingPong(Time.time * 3 * speedLerp, 1.0));

This is working for me.
using UnityEngine;
using System.Collections;
public class Tile : MonoBehaviour {
public Vector2 gridPos = Vector2.zero;
Renderer r;
public Color colorStart = Color.red;
public Color colorEnd = Color.green;
public float duration = 1.0F;
private float lerp;
// Use this for initialization
void Start () {
r = GetComponent<Renderer>();
lerp = Mathf.PingPong(Time.time, duration) / duration;
}
// Update is called once per frame
void Update () {
}
void OnMouseEnter()
{
r.material.color = Color.Lerp(colorStart, colorEnd, lerp);
//r.material.color = Color.black;
Debug.Log("X pos = "+ gridPos.x + "Y pos = "+ gridPos.y);
}
void OnMouseExit()
{
r.material.color = Color.Lerp(Color.white, Color.white,lerp);
}
}

set a bool type for color like
bool colorchange = false;
public void OnCollisionEnter (Collision col)
{
Debug.Log ("collide");
colorchange = true;
if (colorchange) {
transform.GetComponent<Renderer> ().material.color = Color.red;
}
}

Related

Unity: Make color of MeshRenderer transparent

I have a little question. I have a cube which has a Mesh Renderer and I gave it a default black material as its color. Now I would like to make the object more transparent when it touches something. I already set the Rendering Mode to Fade or Transparent. The tag is also set. This is my code:
public GameObject cube;
private Color tempcolor;
void Start()
{
tempcolor = cube.GetComponent<MeshRenderer>().material.color;
}
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Object"))
{
tempcolor.a -= 0.1f;
}
}
My code doesn't do the job. When I Debug.Log tempcolor.a it goes down but nothing happens with the cube. I also tried normal Renderer but it didn't work. Any idea?
I would be grateful if you can help me out
Kind regards
You don't need tempColor and Start() event, just save the main component temporary.
public void OnTriggerEnter(Collider other)
{
var meshRenderer = cube.GetComponent<MeshRenderer>();
if (other.CompareTag("Object"))
{
var color = meshRenderer.material.color;
color.a -= .1f;
meshRenderer.material.color = color;
}
}

Fading UI text from object Checksphere and interact

I'm trying to come up with a generic rule that I can add to any GameObject. Items like tables, chairs etc that once collided and interacted fade in the white text, then after a few seconds the text fades out.
Ideally I'd be able to offset the position of this text with a Vector3 so I can position it around my character
At the moment I have, some code but the CrossFade.Alpha doesn't seem to work. this might or might not be the best way to go about this, I'm open to new ideas
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Qwerty : MonoBehaviour
{
public float Radius = 1f;
public Text TextToUse;
[SerializeField] private LayerMask playerMask;
private bool isInSphere;
// Start is called before the first frame update
void Start()
{
isInSphere = false;
}
// Update is called once per frame
void Update()
{
isInSphere = Physics.CheckSphere(transform.position, Radius, playerMask);
if (isInSphere && Input.GetKey(KeyCode.F) == true)
{
// Check if collision is detected and F is pressed
isInSphere = true;
Debug.Log("Hello");
//Fade in over 2 seconds
TextToUse.CrossFadeAlpha(1, 2f, false);
}
else if (!isInSphere && !Input.GetKey(KeyCode.F))
{
//Fade out on leave over 2 seconds
isInSphere = false;
TextToUse.CrossFadeAlpha(0, 2f, false);
}
}
}
Description
Tweens the alpha of the CanvasRenderer color associated with this Graphic.
Creates a fading effect on a Graphic with a CanvasRenderer attached. Choose an alpha level to fade to, and pick the speed of the fade to see a smooth fade over time. UI Images and Text are some of the elements that you are able to apply this effect to.
CrossFade.Alpha needs a canvas that has CanvasRenderer attached to work.

If disable/enable collider the animator doesn't work anymore

I have a character with BoxCollider2D and Animator components. I need to change a physic material's friction dynamically so I use the next function:
private void ChangeFriction(float friction)
{
boxCollider.sharedMaterial.friction = friction;
boxCollider.enabled = false; // The friction won't be changed if I won't reset the collider
boxCollider.enabled = true;
}
The problem is that after an execution of this function the walking animation isn't played anymore totally. If I comment two last lines then all works perfectly but the friction doesn't change, just like To be or not to be.
How can I fix this issue?
I have been using this piece of code to access friction and change it and it works without enabling and disabling the collider. I can see it changes in Editor as well.
private Collider2D col;
void Start () {
col = gameObject.GetComponent<Collider2D>();
}
void Update () {
if(Input.GetKeyDown(KeyCode.Mouse0))
{
col.sharedMaterial.friction = 1;
}
if (Input.GetKeyDown(KeyCode.Mouse1))
{
col.sharedMaterial.friction = 0.5f;
}
Debug.Log(col.sharedMaterial.friction);
}

Scroll texture on Sprite in Unity for background scrolling effect, not working

I've been trying to achieve a scrolling background effect using a Sprite in a 2D Unity project.
I've seen this code being used on 3D objects with a MeshRenderer to achieve the effect but this does not seem to work on a Sprite with SpriteRenderer. Does anybody know why?
public class ScrollingTexture : MonoBehaviour {
public float ScrollSpeed = -0.5f;
private Vector2 _savedOffset;
private Renderer _renderer;
private void Start ()
{
_renderer = GetComponent<Renderer>();
_savedOffset = _renderer.material.mainTextureOffset;
}
private void Update()
{
float x = Mathf.Repeat (Time.time * ScrollSpeed, 1);
Vector2 offset = new Vector2(x, _savedOffset.y);
_renderer.material.mainTextureOffset = offset;
}
private void OnDisable()
{
_renderer.material.mainTextureOffset = _savedOffset;
}
}
UPDATE:
To get it to work properly I have added a new material as suggested and set its shader to Unlit/Transparent. I also had to make sure the Sprite itself had its Wrap Mode set to Repeat. I did not fix the Inspector Warning yet.
You get this warning in the inspector
I managed to get it scrolling by just creating a New Material and assigning it to the GameObject, then changing the Shader to Sprites/Diffuse.

how to slowly change the skybox color in unity 5

I am trying to change the color or tint of my skybox so it will slowl turn to black. I have looked for a while now and I still cant find anything on this. Here is my code right now:
public class SkyboxColorChanger : MonoBehaviour
{
public Color colorStart = Color.blue;
public Color colorEnd = Color.red;
public float duration = 1.0F;
private void Update ()
{
float lerp = Mathf.PingPong(Time.time, duration) / duration;
RenderSettings.skybox.SetColor("_Tint", Color.Lerp(colorStart, colorEnd, lerp));
}
}
The problems with this one are:
in the options it appears this would only work if the sky was a solid color.
when I did get it to work it changed at a very fast rate (im looking for a very long time between the changes).
Thanks for looking!
Try this:
public float step = 0;
private void Update ()
{
RenderSettings.skybox.SetColor("_Tint", Color.Lerp(colorStart, colorEnd, step));
step += Time.deltaTime / duration;
}

Categories

Resources