How to change conditions in Update() unity c# - c#

I have created navMeshand agent. For target I used two empty object.
For each empty object I created two buttons.
If I click on white button agent moves to empty target first again I click on red button agent moves to 2nd empty target.
I am facing problem when I want move agent from target-2 to target-1.
How I can move that agent to taeget-1?
See video for better understanding
video link https://youtu.be/zRKHdMeQsi0
Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class SampleAgentScript : MonoBehaviour {
public Transform target , target2;
NavMeshAgent agent;
private static bool start1=false , start2=false;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
public static void buttonClick()
{
//if white button click
start1 = true;
}
public static void buttonClick2()
{
//if red button click
start2 = true;
}
void Update()
{
if (start1) //if white button click moves to targer-1
{
agent.SetDestination(target.position);
}
if (start2) //if red button click moves to targer-2
{
agent.SetDestination(target2.position);
}
}
}

May be this will help.
public static void buttonClick()
{
//if white button click
start1 = true;
start2 = false;
}
public static void buttonClick2()
{
//if red button click
start2 = true;
start1 = false;
}

You have forgotten to alternate the state by resetting the boolean values to false. As you have set boolean values in the button click handler, so you can alternate states in the update function as well.
void Update()
{
if (start1) //if white button click moves to targer-1
{
agent.SetDestination(target.position);
start1=false;
}
if (start2) //if re button click moves to targer-2
{
agent.SetDestination(target2.position);
start2=false;
}
}

When you click the second button both of the conditions become true and in each frame you are setting two different destinations.
public Transform dest, target , target2;
public void buttonClick()
{
dest = target;
}
public void buttonClick2()
{
dest = target2;
}
void Update()
{
agent.SetDestination(dest .position);
}

Related

References to the panels missing

When I click the OK button of the win or lose panel on the GameScene it takes me back to the MenuScene and shows the title screen instead of the level select screen.
The references to the paneles are missing before changing scene, how can I keep them through them?
StartManager
public GameObject startPanel, levelPanel;
// Start is called before the first frame update
void Start()
{
startPanel.SetActive(true);
levelPanel.SetActive(false);
}
public void PlayGame()
{
startPanel.SetActive(false);
levelPanel.SetActive(true);
}
public void Home()
{
startPanel.SetActive(true);
levelPanel.SetActive(false);
}
I expected the levelPanel to be active
public GameObject startPanel, levelPanel;
public static bool OpenLevelPanel;
// Start is called before the first frame update
void Start()
{
// Check OpenLevelPanel Bool Setting That;
startPanel.SetActive(!OpenLevelPanel);
levelPanel.SetActive(OpenLevelPanel);
}
public void PlayGame()
{
startPanel.SetActive(false);
levelPanel.SetActive(true);
}
public void Home()
{
startPanel.SetActive(true);
levelPanel.SetActive(false);
}
On Button Ok Click
StartManager.OpenLevelPanel = true;
//Switch Scene...

How do I change a scripts variable from a different object?

In my Unity project I have a shrink button and a ball. When I click the shrink button the ball should play the shrinking animation.
I am trying to change the "shrink" variable so the animation will know to play.
Shrink button code:
private ShrinkBall referenceScript;
void Start()
{
referenceScript = ball.GetComponent<ShrinkBall>();
}
void OnMouseDown()
{
if (referenceScript.shrink == true)
{
referenceScript.shrink = true;
} else
{
referenceScript.shrink = false;
}
}
Ball script:
public bool shrink = false;
private Animator shrinkAnim;
void Start()
{
shrinkAnim = GetComponent<Animator>();
}
void Update()
{
if (shrink == false)
{
shrinkAnim.SetBool("shrink", false);
} else
{
shrinkAnim.SetBool("shrink", true);
}
}
When I click the shrink button, the "shrink" variable remains false. I know it's accessing it because it initially told me it was out of scope, so I made it a public variable.
So the animation never plays because shrink doesn't change. Any ideas?
You are never changing the shrink value but make it keep the same value it already has...
You probably rather wanted to do
void OnMouseDown()
{
referenceScript.shrink = !referenceScript.shrink;
}
Then you shouldn't use SetBool all the time in Update but rather only once you change it.
You could e.g. use a method like
public void ToggleShrink()
{
shrink = !shrink;
shrinkAnim.SetBool("shrink", shrink);
}
Then you could simply call it from the first script like
private void OnMouseDown()
{
referenceScript.ToggleShrink();
}

How to know which prefab button I am clicking?

I made a couple of prefab buttons. When I click each one of them they go to the same scene, but I that scene to have different information according to which button I clicked. How can know which was the button I clicked? The function goArtistDetail is the one being called by every button.
I have this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScriptTwo : MonoBehaviour
{
// Use this for initialization
void Start ()
{
Debug.Log("ButtonScriptTwo");
Debug.Log("counter: " + GlobalState.counter);
}
public void goArtistDetail(Button button)
{
GlobalState.counter++;
Application.LoadLevel("ArtistDetail");
}
}
Prefab of the Button
is there any reason why you are trying to use the same method for both calls other than that the same scene is being loaded? If not why not just have a different method for each buttons onClick and set a PlayerPref.
public void ButtonClick_1()
{
GoArtistDetail(1);
}
public void ButtonClick_2()
{
GoArtistDetail(2);
}
// C# Methods start with a Captial
private void GoArtistDetail(int refererBtn)
{
GlobalState.counter++;
PlayerPrefs.SetInt("Referer Button", refererBtn)
Application.LoadLevel("ArtistDetail");
}
An then in the ArtistDetail scene
private void Start()
{
int refererBtn = 1; //Default value
if(PlayerPrefs.HasKey("Referer Button"))
{
refererBtn = PlayerPrefs.GetInt("Referer Button");
PlayerPrefs.DeleteKey("Referer Button");// Remove it if it is use once
}
//Evaluate refererBtn to show what info is relevant
}

Clicking button game logic not working properly

In my script whenever you click a "Button" it adds 1 to your score. When you miss the button 10 times total it loads a new scene and you lose the game. When you click the button it resets the total back to 0. The problem im having is that if you miss the button 9 times and then click it on the 10th time it still counts to 10 and it loads the new screen and you lose.
What it should be doing is resetting it back to 0 and you can continue to play.
loseObject sets the amount to 0 when the game begins and when the button is pressed.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(AudioSource))]
public class ButtonReposition : MonoBehaviour
{
public Button prefab;
public GameObject loseObject;
private int count;
public Text countText;
// Use this for initialization
void Start()
{
count = 0;
SetCountText();
float x = Random.Range(325f, -600f);
float y = Random.Range(250f, -450f);
Debug.Log(x + "," + y);
prefab.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
loseObject.GetComponent<Lose>().amount = 0;
}
public void Move()
{
float x = Random.Range(325f, -600f);
float y = Random.Range(250f, -450f);
Debug.Log(prefab.transform.position.x + "," + prefab.transform.position.y);
prefab.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
loseObject.GetComponent<Lose>().amount = 0;
count = count + 1;
SetCountText();
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
}
}
And on get mouse button down it adds 1 to the total and loads the next scene.
using UnityEngine.Audio;
using UnityEngine.UI;
public class Lose : MonoBehaviour
{
public GameObject Button;
public GameObject Target;
public GameObject loseObject;
public int amount;
public ButtonReposition script;
public void ChangeScene(int changeTheScene)
{
SceneManager.LoadScene(changeTheScene);
}
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
amount += 1;
Debug.Log(amount);
if (amount == 10)
{
SceneManager.LoadScene(2);
Destroy(Button);
}
}
}
}
In other to get this right, you have to find a way to determine when the moue button is down and Button is clicked. You are not doing that now. What you are doing now is checking when left mouse Button is clicked with if (Input.GetMouseButtonDown(0)).
This is one of the cases, where using the Image component is better than using the Button component. Unless you really need the Button component here, the Image component should be used.
This can be done with IPointerDownHandler, IPointerUpHandler interface with their OnPointerDown and OnPointerUp functions.
Disable your ButtonReposition script for now. Use the script below and see if that's doing what you expected. If everything is fine you can then enable your ButtonReposition script and remove the unnecessary stuff inside it.
Attach the ButtonDetector to your Image Component:
public class ButtonDetector : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public bool clicked = false;
public void OnPointerDown(PointerEventData eventData)
{
clicked = true;
//Debug.Log("Pointer Down!");
}
public void OnPointerUp(PointerEventData eventData)
{
//Reset
clicked = false;
// Debug.Log("Pointer Up!");
}
// Use this for initialization
void Start()
{
}
}
Your new Lose script:
public class Lose : MonoBehaviour
{
public GameObject Button;
public GameObject Target;
public GameObject loseObject;
public int missedAmount = 0;
public int clickedAmount = 0;
const int MISSED_MAX_AMOUNT = 10;
//public ButtonReposition script;
public void ChangeScene(int changeTheScene)
{
SceneManager.LoadScene(changeTheScene);
}
private ButtonDetector buttonImage;
void Start()
{
GameObject obj = GameObject.Find("ButtonImage");
buttonImage = obj.GetComponent<ButtonDetector>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (buttonImage.clicked)
{
Debug.Log("Mouse Clicked on Button!");
clickedAmount++;
//Reset missedAmount to 0
missedAmount = 0;
}
else
{
Debug.LogWarning("Mouse Click on SOMETHING ELSE");
missedAmount++;
}
if (missedAmount == 10)
{
Debug.LogWarning("GameOver!");
Debug.LogWarning("Missed 10 times in a row!");
SceneManager.LoadScene(2);
//Destroy(buttonImage.gameObject);
}
}
}
}
I think the easiest fix for you would be to make sure your loseObject script executes after your first script. You can do that with the script execution order. If you go to Edit -> Project Settings -> Script Execution Order you can add your loseObject script and draw it below "Default". Then your other script will execute first and set the amount to 0 as you would expect. However, after it gets set to 0, loseObject will still increment by one, so what you actually want to do is set amount to -1.

Unity3d c#. onClick.AddListener() works once

There's a void in the script, which reloads Canvas. The Canvas contains the Button object. I attach the reload void with the script.
using UnityEngine;
using UnityEngine.UI;
public class Trashscript : MonoBehaviour {
public GameObject Temp;
private GameObject Active;
int Counter;
void Start()
{
Menu();
}
void Menu()
{
Counter++;
if (Active != null) Destroy(Active);
Active = Instantiate(Temp);
GameObject.Find("Text").GetComponent<Text>().text = Counter.ToString();
GameObject.Find("Btn").GetComponent<Button>().onClick.AddListener(Menu);
}
}
First call (from Start) works fine the "Text" element shows "1". After clicking the "Btn" Canvas reloads, but there isn't any "Text", and "Btn" doesn't work (onClick event do nothing).
Help.
I can't tell what your code is doing but each time the Button is clicked, Menu function is called which leads to GetComponent<Button>().onClick.AddListener(Menu) being called again.
You have to move GetComponent<Button>().onClick.AddListener(Menu) out of the Munu function and into the Start() function. You also have to un-register to the Button event in the OnDisable() function.
Below is what your code should look like:
Button button;
void Start()
{
button = GameObject.Find("Btn").GetComponent<Button>();
button.onClick.AddListener(Menu);
}
void OnDisable()
{
button.onClick.RemoveListener(Menu);
}
void Menu()
{
///Put Your Button click code here
}
I solved my problem with changing the GameObject.Find("") to Active.transform.Find("").

Categories