unity object reset button and slider - user-interface

I want to make that on keyboard r button press reset object into position: x112 y8 z153. Object name is Sphere i can rename it.
And i want a gui slider that can change forceadder 50f in game from 0 to 500.
I am a beginner. Just finished begginer tutorials. What code do i need to get? i tried to make that reset button my self but dosent do anything to me it says in debug that its pressed but it dosent reset it. Soo i removed that code.
My code right now:
using UnityEngine;
using System.Collections;
public class ShootMeBall : MonoBehaviour
{
public float forceadder = 500f;
void OnMouseDown()
{
rigidbody.AddForce (transform.forward * forceadder);
rigidbody.useGravity = true;
}
void Awake()
{
Debug.Log ("I am awake.");
Screen.lockCursor = true;
gameObject.renderer.material.color = Color.yellow;
}
}

Here's the solution(You will need to drag the object you're moving into the scripts GameObject variable in the inspector, and the slider into the slider slot):
using UnityEngine;
using UnityEngine.UI;
using System;
public class Example : MonoBehavior
{
public GameObject go;
public Slider slider;
private float force;
void Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
go.transform.position = new Vector3(112f, 8f, 153f);
}
force = (float)slider.value;
}
}
Don't forget to set the min/max values of the slider, and the value "Use whole numbers" to true if it matters.

Related

How to move a cube 3 second in one direction, and next 3 seconds in oppposite direction, alternatively

I am new to unity, and trying something like below, but I can either move only in one direction, or not moving at all.
My cube is a trigger, and is not using gravity. I have checked the Kitematic box. I am trying to make the cube move to and fro, so that player have difficuly collecting it.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class movedanger : MonoBehaviour
{
private int mytime = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
MyMover(mytime);
}
void MyMover(int mytime)
{
if (mytime <= 3)
{
transform.Translate(Vector3.forward * Time.deltaTime);
mytime++;
}
else
{
transform.Translate(-Vector3.forward * Time.deltaTime);
mytime = 1;
}
}
}
What you are looking for is to and fro movement of an object. You can achieve this with Mathf.PingPong() function instead of using translate. I have tested it with a cube, you can set the minimum and maximum distance it should move to and the speed at which it travels. Since you want the cube to move 3 seconds in one direction at a time. You can calculate the speed as distance/time so the max distance it should travel to from the current distance and the time (3 seconds) it takes. Hope this helps.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour {
public float min = 2f;
public float max = 8f;
public float SpeedOfMovement = 2f;
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = new Vector3 (Mathf.PingPong (Time.time * SpeedOfMovement, max - min) + min, transform.position.y, transform.position.z);
}
}
With InvokeRepeating you will call the same MoveCube method every 3 seconds.
using UnityEngine;
public class MoveDanger: MonoBehaviour
{
public bool isForward = false;
private void Start()
{
InvokeRepeating("MoveCube", 0f, 3f);
}
private void MoveCube()
{
if (isForward)
{
transform.Translate(Vector3.back);
isForward = false;
}
else
{
transform.Translate(Vector3.forward);
isForward = true;
}
}
}
Honestly the best and easiest way to do something like this, once you get used to it, is just to
Use Unity's incredibly simple animator system:
(Essentially just click "new animation" and then drag the object around as you want it animated.)
There are 100s of tutorials online explaining how to use it.
It's one of those things where once you use it and see how easy it is, you will do a "facepalm" and never bother again with other ways.
It's really "the Unity way" to achieve the goal here, dead easy and flexible.

Getting errors when i try to get game to restart when i hit an obstacle or fall of ground

Please excuse me I'm a complete novice at all this but I'm trying to make a game following "Brackeys How To Make A Video Game" I'm on video 8 if that helps. I can't seem to find what i have done wrong i have added my scripts for "player movement", "player collision" and "game manager". Please if there is anything else you need to help me please ask i really don't want to give up just yet was really enjoying doing this.
Thank you all
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 2000f; // Variable that determines the forward force
public float sidewaysForce = 500f; // Variable that determines the sideways force
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) // If the player is pressing the "a" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
public class PlayerCollision : MonoBehaviour {
public PlayerMovement movement; // A reference to our PlayerMovement script
// This function runs when we hit another object.
// We get information about the collision and call it "collisionInfo".
void OnCollisionEnter (Collision collisionInfo)
{
// We check if the object we collided with has a tag called "Obstacle".
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false; // Disable the players movement.
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
bool gameHasEnded = false;
public float restartDelay = 1f;
public GameObject completeLevelUI;
public void CompleteLevel ()
{
completeLevelUI.SetActive(true);
}
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
when i fall off ground:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.FixedUpdate () (at Assets/Scripts/PlayerMovement.cs:32)
when i hit an obstacle:
NullReferenceException: Object reference not set to an instance of an object
PlayerCollision.OnCollisionEnter (UnityEngine.Collision collisionInfo) (at Assets/Scripts/PlayerCollision.cs:15)
It seems to me that FindObjectOfType<GameManager>() is returning null, which is causing a null reference exception when you attempt to call the EndGame function. This most likely means that there is no object in your scene with the GameManager component on it. The solution to this problem is simple:
Create an empty object in your scene and add the GameManager component to it. This will fix the error in this instance, but it could happen in the future if you're not careful. It is also a good idea to check if you found an object or not before calling functions on it:
GameManager gm = FindObjectOfType<GameManager>();
if (gm != null)
{
gm.EndGame();
}

Destroying a prefab from mouse click raycast

I want to destroy or remove a spawning prefab from my scene when the mouse clicks on the gameobject. I'm trying to use the code below from the Unity docs, however I'm presented with the following error:
object reference not set to the instance of an object.
This script is attached to my main camera. onclick crashes the game. Can anyone see where this is going wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class onClickDestroy : MonoBehaviour
{
public GameObject destroyCube;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit(); //*
if (Physics.Raycast(ray, out hit)) //**
{
print("true" + hit.point);
}
}
}
}
Solution 1
Make sure your Camera is really tagged as MainCamera
if not click there and select MainCamera from the list
Solution 2
Get and check the main camera at game start
priavte Camera _camera;
privtae void Awake()
{
_camera = Camera.main;
if(!_camera)
{
Debug.LogError("No Camera tagged MainCamera in Scene!");
enabled = false;
}
}
Solution 3
Or instead of using Camera.main at all instead get the Camera component directly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class onClickDestroy : MonoBehaviour
{
public GameObject destroyCube;
privtae Camera _camera;
private void Awake()
{
_camera = GetComponent<Camera>();
}
// Update is called once per frame
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
print("true" + hit.point);
}
}
}
}

How to change button image on click Unity

I got unlock button for game, it works,but I want to user himself can press button, and then button image change. As you can see in code below when score is >= 10, buttons image change immediately. How can I achieve that?
public GameObject lockBtn;
Image lockComp;
public Sprite myLockImage;
public Sprite myLockSecondImage;
/////////////////////////////////////////
lockComp = lockBtn.GetComponent<Image> ();
if (bestScore >= 10) {
lockComp.sprite = myLockImage;
}
else
{
lockComp.sprite = myLockSecondImage;
}
Simply add an event listener to your button so as to change the image.
lockComp.sprite = myLockSecondImage;
if (bestScore >= 10) {
lockBtn.GetComponent<Button>().onClick.addEventListener( OnLockButtonClicked ) ;
}
// ...
private void OnLockButtonClicked()
{
lockComp.sprite = myLockImage ;
}
Be carefull to not add this snippet of code into the Update function. Otherwise, you will add a new event listener every frame
Saving the "unlocked state" of the button into a file so as to not show the unlocked sprite when the user starts the game again could be a good idea.
Put your code in a file and class named ButtonScript and in a method named OnButtonClick()
public class ButtonScript : MonoBehaviour {
public void OnButtonClick(){
lockComp = lockBtn.GetComponent<Image> ();
if (bestScore >= 10) {
lockComp.sprite = myLockImage;
}
else
{
lockComp.sprite = myLockSecondImage;
}
}
}
Then add this script on your Button and in the OnClick event add a reference to the Button and his Method:

Use parameters for variable animation

I'd like to animate my Score-GUI text counting up to a variable value but there are two things in my way:
1: How can I animate to a variable instead of a fixed value?
2: Why can't I add own properties (like int) to my script and animate them?
For #2 I created a property in my script. Yet the editor won't show it in the AddProperty-dialog (as shown below):
public int currentScore = 0;
public int score {
get { return currentScore; }
set { this.currentScore += value; }
}
EDIT: The animator is set up in the most basic way:
Since you only have 1 Animation. An Animator is irrelevant to the solution. This is tested and working. Now you need to make the Animation a Legacy type to get this working because we are not going to use the Animator.
Click the Animation on the Project -> look at the upper right section of the Inspector view, there is a little button there which will drop down a selection. "Debug" then Check the Legacy.
Set your Animation to whatever you want. I force the WrapMode in the script to be wrap mode once. So it will only play once.
Now in the Animation Component make sure you select the Animation that you want by default or it wont work. Cause we only use anim.Play(); Without parameters meaning, run the default animation that is set.
I created a Text UI and added an Animation that alpha is 0 from the start and at the end point making it 1. You have to do that on your own.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MyScore : MonoBehaviour {
// Use this for initialization
public int currentScore = 0;
public GameObject Myscore; // Drag the GameObject that has the Animation for your score.
public Text myScoreText; //Drag in the Inspector the Text object to reference
public Animation anim;
public int score
{
get { return currentScore; }
set { this.currentScore += value; }
}
void Start()
{
anim = Myscore.GetComponent<Animation>(); // Reference the Animation Component.
anim.wrapMode = WrapMode.Once; // Legacy animation Set to play once
AddScore();
}
public void AddScore()
{
score += 10;
myScoreText.text = score.ToString();
anim.Play();
Debug.Log("Current Score is "+ score);
Invoke("AddScore", 2);
}
}
Good luck.

Resources