I'm wanting to have two textures switch when ever I press the space bar in my project. But when I do, nothing is happening.
can anyone see what I'm doing wrong with my logic? I had this working with switching between 2 shaders, but not it is materials, it isn't working. I'm very confused by this.
void Switch()
{
Debug.Log(gameObject.renderer.material.name);
if(Input.GetButtonDown("Jump"))
{
diffuse = false;
//if(gameObject.renderer.material == diffuse_Material)
}
else
{
diffuse = true;
}
if(diffuse == true)
{
gameObject.renderer.material = mask_Material;
print("1");
Debug.Log(gameObject.renderer.material.name);
}
else
{
gameObject.renderer.material = diffuse_Material;
print("2");
Debug.Log(gameObject.renderer.material.name);
}
My codes changes the material once, but doesn't change back again when I press the space bar again.
update
I've taken my code out of the update method and placed it in its own one. I've since modified it to be a "simple" bool check. Now when I play the game my object starts with the material I first want on it, but when I hit space, it only changed the material for a fraction of a second.
How can I do it so that on the press of a single button, my bool toggles between true and false. I thought i had it, but I guess I don't. My debug log now looks like this:
DepthMask (instance)
1
DepthMask (instance)
2
Diffuse (instance)
Diffuce (instance)
DepthMask (instance)
DepthMask (instance)
1
I think the problem is the following:
When the user presses the jump key the boolean gets set to true, the material changes and its all good. BUT then the update method gets called again, and followed by that I'm assuming your Switch method also.
Input.GetButtonDown("Jump") will now evaluate to false, causing your boolean value diffuse to become true again, and the material changes back.
Is the material supposed to toggle everytime the users presses the Jump button? If so, change your code to (the else statement can be completely removed):
void Switch()
{
Debug.Log(gameObject.renderer.material.name);
if(Input.GetButtonDown("Jump"))
{
diffuse = !diffuse;
// material only needs to change if diffuse changed
if(diffuse)
{
gameObject.renderer.material = mask_Material;
print("1");
Debug.Log(gameObject.renderer.material.name);
}
else
{
gameObject.renderer.material = diffuse_Material;
print("2");
Debug.Log(gameObject.renderer.material.name);
}
}
}
EDIT: included the entire Switch method.
You could try to compare
renderer.sharedMaterial
instead of
renderer.material
to get the non-instanced version of the material. Something like this:
public Material a;
public Material b;
void Update ()
{
if (Input.GetButtonDown("Jump"))
{
if (renderer.sharedMaterial == a)
{
gameObject.renderer.material = b;
}
else
{
gameObject.renderer.material = a;
}
}
}
Related
I'm very new to unity and I'm making a simple tag game with car like players. However, I'm having problems with my trigger collider. When I tag the other car it kind of flickers the is tagged true/false. Here is my code.
public Color TaggedColor;
public Color NoTaggedColor;
public bool Tagged;
// Start is called before the first frame update
void Start()
{
Tagged = true;
GetComponent<Image>().color = TaggedColor;
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "P2")
{
if (Tagged == false)
{
Tagged = true;
GetComponent<Image>().color = TaggedColor;
}
else
{
if (Tagged == true)
{
Tagged = false;
GetComponent<Image>().color = NoTaggedColor;
}
}
Debug.Log("TAG!");
}
}
void GotTagged()
{
if (Tagged == false)
{
Tagged = true;
//GetComponent<Image>().color = TaggedColor;
}
}
void TaggedOtherPlayer()
{
if (Tagged == true)
{
Tagged = false;
GetComponent<Image>().color = NoTaggedColor;
}
}
I have a Second code for P2 that the only change is the start and the tag is P1. I'm not sure if this problem is something in my code or if it's the collider it's self. If anyone has any idea why this is happening I would love to hear it!
Update: I bevile the issue is coming from the Colliders because I have an empty as a child of both players that is the trigger collider. However when I tag one the other trigger goes off as well. Should I have only one trigger? And if so how would I go about doing it?
Thanks
once you tag a player SetActive(false) the empty triggers for about 1 second or so. If you had a button that whenever its pressed it changes s value from true to false the false to true if you press and hold that button it will "flicker" back and forth between true and false. Thats what's happening with your players the trigger is constantly being pulled while you're touching so make it inactive for long enough for you to not be touching anymore. I hope that makes sense.
How can I make this code work properly? It's old but all I could find. I'm trying to make a mania type of game and I need the 4 buttons to work properly. I've tried to change the code somehow and managed to get the button be pressed down, but the thing is that the button won't go back up, they just stay as they are, pressed down. If there are any people who've done something similar to this please help and even those who've not please help too. Thanks.
private SpriteRenderer theSR;
public Sprite defaultImage;
public Sprite pressedImage;
public KeyCode keyToPress;
// Start is called before the first frame update
void Start () =>
theSR = GetComponent<SpriteRenderer>();
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(keyToPress))
{
theSR.sprite = pressedImage;
}
if(Input.GetKeyDown(keyToPress))
{
theSR.sprite = defaultImage;
}
}
}
The two conditions are identical. You probably meant to negate the later to set the button's image do defaultImage, when the key "is not down".
if (! Input.GetKeyDown(keyToPress))
{
theSR.sprite = defaultImage;
}
An if-else block whould be even neater:
if (Input.GetKeyDown(keyToPress))
{
theSR.sprite = pressedImage;
}
else
{
theSR.sprite = defaultImage;
}
Currently I'm simply trying to change the sprites candle from unlit to lit when the player has 'picked up' both the candle and the matches and the candle will 'go out' after a certain amount of time. However, when the space bar is pressed the transition from unlit to lit isn't occurring, even though the debug log is returning true when it should. I'm posting here to get some guidance as I have spent most of the day looking online and literally have no idea how to proceed.
Basically the images I am trying to transition between are two different images which are in the sprites folder under assets.
This is what I've got so far.
//the two sprites transition
public Sprite unlitCandle;
public Sprite litCandle;
private SpriteRenderer spriteRenderer;
bool pickUpMatches = false;
bool pickUpCandle = false;
float timeRemaining =5;
bool candleLit = false;
// Use this for initialization
void Start () {
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer.sprite == null)
spriteRenderer.sprite = unlitCandle;
}
// Update is called once per frame
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("Matches"))
{
collision.gameObject.SetActive(false);
pickUpMatches = true;
}
if (collision.gameObject.CompareTag("UnlitCandle"))
{
collision.gameObject.SetActive(true);
pickUpCandle = true;
}
}
public void CandleTimer()
{
if (candleLit == true)
{
timeRemaining = 5;
timeRemaining -= Time.deltaTime;
if (timeRemaining <= 0)
{
candleLit = false;
spriteRenderer.sprite = unlitCandle;
}
}
}
public void ChangeSprite()
{
if (spriteRenderer.sprite == unlitCandle)
{
spriteRenderer.sprite = litCandle;
}
}
void Update () {
if (pickUpCandle == true && pickUpMatches == true)
{
//Debug.Log(candleLit);
if (Input.GetKey(KeyCode.Space) && !candleLit)
{
CandleTimer();
ChangeSprite();
Debug.Log(timeRemaining);
candleLit = true;
//Debug.Log(candleLit);
}
}
}
}
Try comparing with a method like equals() instead of == in
spriteRenderer.sprite == unlitCandle
Because right now you are just comparing references and not the objects.
At least I think thats the problem.
There are a few possible issues with your code. First, you are calling changeSprite at the top of Update, which means that it is unconditionally being called every frame. Therefore, after a single frame of your candle being unlit, it will immediately change its sprite to litCandle.
I assume that the reason you are calling changeSprite every frame is in order to process the timer if you have a lit candle already. Really, you should move the code to process the timer (your whole second if statement in changeSprite) to a separate function and name it something like processCandleTimer. Call that at the top of Update and save the changeSprite method to only be called on the keypress.
Lastly, the issue that I suspect is giving you the most trouble is that you aren't resetting your timer, timeRemaining. The first time you light the candle the timer will go down to 0 after the 5 seconds pass. Every time changeSprite is run after that, you will change the sprite to litCandle in the first if statement and then immediately change it back to unlitCandle because the timer is 0 in the second. To remedy this, you need to add a line like timeRemaining = 5.0f; when the key is hit.
I need help with a game I am creating. I am building the game with the Unity engine and am pretty new to C# coding. I am creating a 2d game where the player controls the color of a square and must change it to the correct color as when it passes a certain colored object. The player changes colors great and the objects are triggers. When a player passes the trigger if its not the right color the player dies. Well that works perfect but only for the first object the next one no matter the color of the player the object dies. I have tried if's in if statements and else if's I can't seem to figure it out. Your help would be greatly appreciated!
Here is the code for the player
void OnTriggerEnter (Collider other)
{
if (other.transform.tag == "Blue") {
blue = true;
}
else {
blue=false;
}
if (other.transform.tag == "Red") {
red = true;
}
else {
red =false;
}
if (other.transform.tag == "Blue" && GameObject.Find ("Blue").GetComponent<Blue> ().mb == false) {
yield return 0;
Die ();
} else if (other.transform.tag == "Red" && GameObject.Find ("Red").GetComponent<Red> ().mr == false) {
Die ();
}
}
Here is the code for each different colored object. This one happens to be blue.
void Update () {
if (GameObject.Find ("Player").GetComponent<Movement> ().blue == true && GameObject.Find ("Player").GetComponent<Movement> ().playerBlue == true) {
mb = true;
} else {
mb = false;
}
if (!GameObject.Find("Player").GetComponent<Movement>().blue) {
mb = false;
}
}
Your execution order is a little messy, that's probably why it's not working. Try to make all your logic follow one path, not two. Right now, you are:
(1)Colliding, (2) setting some boolean variables, (3)checking some variables, (4)optionally dying.
At a separate time in a separate class, set the boolean that was set in step 1 and setting the variable that's checked in step 3
This is what we call spaghetti code. It's all twisted together. Can you think of a way to untangle it, so the two bits of logic don't mutually depend on each other?
For example, I see in the latter block of code, you're checking whether the player is blue. Could you instead run that code when the player sets blue (or sets blue=false)?
Edit: I know this isn't strictly answering your question, but this untangling is the first step of the problem solving process.
I'm a beginner in Kinect Programming. Yet I read different tutorials and texts about it. Furthermore I was working on the code examples ("Controls Basis-WPF").
Unfortunately none of the sources teach me how to code grabbing and releasing in a way that I understand.
I would like to create dynamically KinectTileButtons. While the program is running the user should be able to place the buttons to the positions he prefers. The player uses his hand as the cursor.
For example:
There is a button b1 on the top left corner.
While the hand of the user is not on b1, the button doesn't change his position.
If the user's hand is on the button AND he makes the "GRAB"-gesture, the position of the button is like the position of his hand (variable position). When he RELEASES, the position of button is constant and will not change until the user is grabbing for the button the next time.
I'm very thankful for any advices, suggestions or code examples, because I really don't know how I should continue to work on this problem.
Thanks in advance
derpate
What you should be going for is to change the location of the buttons on the window. I would have some global bools to signify is they are grabbing and holding. Then I would put a conditional in the update to move the label to the position of the hand. Here's some pseudo-code:
bool grabbing = false;
bool selected = false;
var button;
var handElement;
Start()
{
button = window.Button;
handElement = window.handElement;
...
sensor.Start();
}
Update() //all frames ready
{
using (SkeletonFrame sf = e.OpenSkeletonFrame())
{
... //get skeleton and position
... //tell if grabbing
if (/*however you do the grab gesture*/)
grabbing = true;
if (selected && grabbing)
{
button.X = handElement.X;
button.Y = handElement.Y;
}
}
}
Button_OnClick()//or whatever it is called for the Kinect UI control
{
selected = true;
}
Sorry for the pseudo-code, I just haven't worked with the Kinect UI before, and I didn't want to have half pseudo-code with the elements I don't know, however I know that it has events like OnClick() for when it is held, and I don't know what you mean by "GRAB" gesture but I assume you know how to implement it if you know what it is. Good luck!
Know also this only works for one button. If you were doing this for many, I would suggest a class... something like:
class MoveableButton : KinectButton//again, don't know the exact name of this
{
private int X, Y;
private bool selected = false, grabbing = false;
public void Selected()
{
selected = true;
}
public void Grabbed()
{
grabbing = true;
}
public void LetGo()
{
grabbing = false;
selected = false;
}
public void Update(UIElement hand)
{
if (selected && grabbing)
{
this.X = hand.X;
this.Y = hand.Y;
}
}
}
This you would then call the appropriate methods during certain frames, I would have an array of them to loop through for Update.