I have no idea how to make an object translucent at the bottom but opaque at the top. My object is a 2D square.
I tried this but it didn't work:
using UnityEngine;
using UnityEngine.UI;
public class SquareColorChanger : MonoBehaviour
{
public Color startColor;
public Color endColor;
private Image _image;
private void Start()
{
_image = GetComponent<Image>();
}
private void Update()
{
float lerpValue = Input.GetAxis("Horizontal"); // this could be replaced with any other value that goes from 0 to 1
_image.color = Color.Lerp(startColor, endColor, lerpValue);
}
}
Lerping a color would change it over time. An image has only one Color value.
For what you want to to you either need to either put a gradient texture in the alpha channel which would be the easiest solution for this or create your own shader.
How to create gradient in shader graph you could follow this and make sure to put your gradient into alpha channel.
Related
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.
I have an object that I upgraded to the URP Sprite-Lit-Default material, but since I did that, the code I wrote to set the alpha color doesn't work at all. Upon further testing, I realized that it doesn't seem to work with red, green, blue, or alpha.
Color c = rend.material.color;
c.a = 120;
rend.material.color = c;
In the code above, rend references my sprite renderer. What do I have to do to change the color values from code on the upgraded material? I would like to use some lighting effects, so I don't wanna just switch to something else that doesn't support URP 2D lighting.
Try this :
//Attach this script to any GameObject in your scene to spawn a cube and change the material color
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
//Create a new cube primitive to set the color on
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
//Get the Renderer component from the new cube
var cubeRenderer = cube.GetComponent<Renderer>();
//Call SetColor using the shader property name "_Color" and setting the color to red
cubeRenderer.material.SetColor("_Color", Color.red);
}
}
https://docs.unity3d.com/ScriptReference/Material.SetColor.html
I am new to unity engine
how to put color on the cube ?
using UnityEngine;
using System.Collections;
public class cor_cube : MonoBehaviour {
public Color colorStart = Color.red;
public Color colorEnd = Color.green;
public float duration = 1.0F;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
}
void Update() {
float lerp = Mathf.PingPong(Time.time, duration) / duration;
rend.material.color = Color.Lerp(colorStart, colorEnd, lerp);
}
} (I don't want like that)
I want a fixed color.
I want a fixed color.
It looks like you don't want to lerp from one color to another. You just want to set the color.
Below are the ways to change color:
Method 1: Predefined Colors
void Start() {
rend = GetComponent<Renderer>();
rend.material.color = Color.blue;
}
There many other predefined Colors such as Color.blue,Color.white,Color.black,Color.green and Color.gray.
Method 2: Custom Color with RGB or RGBA values
You can also create a custom color that is NOT defined in the Color structure.
The format is in RGBA(Red,Green,Blue,Alpha). The values are float numbers from 0.0 to 1.0.
Full Red Color
rend.material.color = new Color(1,0,0,1);
Full Blue Color
rend.material.color = new Color(0,1,0,1);
Full Green Color
rend.material.color = new Color(0,0,1,1);
Half Way Visible Blue Color
rend.material.color = new Color(0,1,0,0.5f);
Hidden Blue Color
rend.material.color = new Color(0,1,0,0);
Method 3: HSV Color
rend.material.color = Color.HSVToRGB(0,0,0);
I can't go on and on but this should get you started. Make sure to create a material in Editor and assign it to the cube so that the default one wont be used. You only need to create one and use it for all your cubes. When you change the color, a new material will be created for you. If you don't want that, use rend.sharedMaterial.color instead of rend.material.color.
In Unity 5, things changed. To get the alpha to change, you have to select the material and change the Rendering Mode from Opaque(default) to Fade or Transparent. So old tutorials may not work because of this.
Create a material with the shader Unlit/diffuse on it. Set the texture to a plain white texture adn set the color of the material.
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;
}
}
Alright, let's say that I have a tile texture of some floor or something. And I'd like that my player will walk on that.
How can I set this tile to make it a as a floor?
I need this tile texture to be all over the screen width right?
How am I doing it?
Thanks
If you want a really easy way, here it is:
First you create a new Class and name it Tile:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework; // Don't forget those, they will let you
using Microsoft.Xna.Framework.Content; // access some class like:
using Microsoft.Xna.Framework.Graphics; // Texture2D or Vector2
namespace Your_Project _Name
{
class Tile
{
}
{
So far so good, now create the Texture and Position in your class just like this:
namespace Your_Project _Name
{
class Tile
{
Texture2D texture;
Vector2 position;
public void Initialize()
{
}
public void Draw()
{
}
}
{
As you can see I also created two Methods, Initialize and Draw, now we will Initialize our
texture and position for the tile texture in the public void Initialize(),
I don't know how you use your ContentManager but here is a easy way:
public void Initialize(ContentManager Content)
{
texture = Content.Load<Texture2D>("YourfloorTexture"); //it will load your texture.
position = new Vector2(); //the position will be (0,0)
}
Now we need to draw our texture a number of time how will we do that? The way thasc said, the code can be more complex but here is one that you will understand, I will add a SpriteBatch so I can Draw. All this is done in the public void Draw():
public void Draw(SpriteBatch spriteBatch)
{
for (int i=0; i<30;i++) //will do a loop 30 times. Each Time i will =
//a valor from 0 to 30.
{
spriteBatch.Draw(texture, position, Color.White);
//Will draw the texture once, at the position Vector2
//right now position = (0,0)
spriteBatch.Draw(texture, new Vector2((int)i,(int)i), Color.White);
//Will Draw the texture 30 times, the first time on the position (0,0)
//Second Time on (1,1) .. third (2,2) etc...
spriteBatch.Draw(texture, new Vector2((int)position.X + (i * texture.Width), (int)position.Y + (i * texture.Height), Color.White));
//Will Draw the Texture 30 times Spaced by the Width and height
//of the texture (this is the code you need)
}
}
I didn't tried it but it should work, now its just a sample, you can figure out the rest. There is a lot of other methods to do it but this one is really easy. Ok, now the final step is to implement this class so go in your principal class where you have all your code and before this:
public Game1()
Create a new instance of your tile class
Tile tile;
and Initialize it in the protected override void Initialize():
tile = new Tile();
tile.Initialize(Content);
Now you have to draw it on the screen go at the end of the class and find protected override void Draw(GameTime gameTime) and call the draw method of our class:
spriteBatch.Begin();
tile.Draw(spriteBatch);
spriteBatch.End();
This is all the steps to complete a plain simple tile system. As I said there is a lot of others methods you just have to read tutorials about them or create them on your own.
If you don't plan on doing anything extra with the tiled background, I'd recommend thasc's solution and tile the sprite in a single call.
To do that, you create a rectangle as large as your background, and pass SamplerState.LinearWrap to SpriteBatch.Begin, then call Draw on the background rectangle.
Rectangle backgroundRect = new Rectangle(0, 0, backWidth, backHeight);
spriteBatch.Begin(..., ..., SamplerState.LinearWrap, ..., ...);
spriteBatch.Draw(backgroundTexture, backgroundRect, Color.White);
spriteBatch.End();
In case you're curious, what this does is create a single polygon that covers the background area, which will grab coordinates off your texture from 0.0f to backWidth. Textures are usually mapped between (0.0f, 0.0f) and (1.0f, 1.0f), which represent the corners of the given texture. If you go beyond these boundaries, TextureAddressMode defines how these coordinates will be treated:
Clamp will cut down the coordinates back into the 0-1 range.
Wrap will wrap the coordinates back to 0, so 0.0 = 2.0 = 4.0 = etc. and 1.0 = 3.0 = 5.0 = etc.
Mirror will also wrap, but mirroring the texture every other pass, basically going left-to-right-to-left-etc. as the polygon is rendered.