Unity: Make color of MeshRenderer transparent - c#

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

Related

Changing Tag of Collided Object Through Collision

Either the script is outdated, or it's not what I need, but I cannot find an answer to this.
To start off, I'm making a pinball styled game, whenever the ball hits a piece, it changes color, but I have multiple colored balls, and I want to lock the color in place as to not have the other balls change them (to make the game a little bit easier). I've provided a script, which may be a little too complex for a simple solution. The problem area is at the bottom with void FixedUpdate.
(I just wanna change a tag ): )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorBlue : MonoBehaviour
{
public Material mat;
public string ballTag;
public bool reset = false;
public bool found = false;
public void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Ball" )
{
gameObject.GetComponent<MeshRenderer>().material.color = Color.blue;
reset = true;
}
}
public void FixedUpdate ()
{
if(reset)
{
GameObject.FindWithTag("Ball");
} found = true;
if(found)
{
GameObject.FindWithTag("Ball").tag = "Untagged";
}
}
}
Instead of searching for the GameObject with the "Ball" Tag which you probably have multiple off in your scene. You can rather just change the tag directly when the collision happens.
Because in the OnCollisionEnter Function you have a reference to the gameObject already, you can just use that to change the tag with collisionInfo.gameObject.tag = "Untagged".
public void OnCollisionEnter (Collision collisionInfo) {
if (collisionInfo.gameObject.CompareTag("Ball") && gameObject.CompareTag("Ball")) {
// Get Mesh Renderer of the Colided Ball Component.
var meshRenderer = collsionInfo.gameObject
.GetComponent<MeshRenderer>();
// Change Color of collided ball to be the same as the ball it collided with.
meshRenderer.material.color = gameObject
.GetComponent<MeshRenderer>().material.color;
// Set Tag to "Untagged" to make sure ball won't change color anymore
colliderInfo.gameObject.tag = "Untagged";
}
}
You could also add additional Code to change the color depending on the current Color of the gameObject. Additionaly I would advise you to use CompareTag(), which checks if the tag even exists in your scene.
If you want to get the collided gameObject you can do that with collisionInfo.gameObject.tag

Unity - Affect only clicked GameObject

I am new to unity, and I tried to create a prefab for a tile in a game. So whenever a user clicks the tile it should change its sprite. The problem is that all the copies (instances) in my game are changing their sprite.
This is what I tried:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject gameObject = this.gameObject;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
}
What am I doing wrong? Thanks in advance
You are detecting if the mouse button is pressed, not if it's pressed over the given tile.
There are several ways to do it, but I would say the standard way is to:
Attach a Collider to the GameObject
Implement OnMouseDown
void OnMouseDown()
{
GameObject gameObject = this.gameObject;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
Like akin said you are changing all sprites on a mouse click, you can raycast to your objects and check if they are hit then change it
Run this part on a script attached to your player or camera
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0f)) {
if (hit.transform.gameObject.GetComponent<yourscript>()) {
hit.transform.gameObject.GetComponent<yourscript>().ChangeSprite();
}
}
}
attach to tile game objects
public class yourscript : MonoBehaviour
{
public void ChangeSprite() {
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
}

Add highlight color feature to SpriteRenderer

I have a 2D unity project for android mobiles,there are a sprite that I added button script on it
now I want use color tint on it .
Change color when I click on it
but the color not changing and I don't want do it with programming
I have tried many things, but still not working
I fixed that before with luck, but now I cant fix it again
anyone know what I am missing?
As it says in the warning, You need to specify a graphic in order to use the color tint. Try dropping in the Image component that has your button sprite here.
Based on the screenshots in your comment, you are mixing SpriteRenderer and the UI System (Image, RawImage, Button). Do not do this.
Read this to understand the difference between both. Once you decide which one to use you can do the the following below.
If you decided to use UI to display your Sprite, do this:
Create new button by going to GameObject-->UI--->Button.
If you prefer to use SpriteRenderer:
Remove any UI component such as Image, RawImage, Button from the GameObject the SpriteRenderer is attached to then manually create a highlight code. The highlight functionality is only built into the Button component. You cannot use the Button component with SpriteRenderer. You have to make your own if you prefer to use SpriteRenderer.
This is easy. Use the EventSystem. Change the color in OnPointerEnter when highlighted and back to its default color in OnPointerExit when pointer exits.
Here is a simple script to do that (Attach to the GameObject with the SpriteRenderer component):
public class SpriteDetector : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
public Color normalColor = Color.white;
public Color highlightedColor = Color.yellow;
public Color pressedColor = Color.blue;
SpriteRenderer sp;
void Start()
{
sp = GetComponent<SpriteRenderer>();
addPhysics2DRaycaster();
}
void addPhysics2DRaycaster()
{
Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
if (physicsRaycaster == null)
{
Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
}
}
public void OnPointerEnter(PointerEventData eventData)
{
sp.color = highlightedColor;
}
public void OnPointerExit(PointerEventData eventData)
{
sp.color = normalColor;
}
public void OnPointerClick(PointerEventData eventData)
{
sp.color = pressedColor;
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}

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.

Set material color with unity 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;
}
}

Categories

Resources