Use parameters for variable animation - 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.

Related

Moving a Prefab in Unity

The purpose of the code is to
make a prefab of "Normal" and "Virus"
make them move in random directions
when they collide, change "Normal" into "Virus" Prefabs
However, I've got stucked on step 2.
I successfuly made "Normal" and "Virus" Prefabs get spawned at random places.
Btw, I have no idea what I should do to supply transform function to Prefabs.
Also, what codes should I use to replace "Normal" Prefabs into "Virus" Prefabs if they collide each other?
These are the codes and pics I used
using UnityEngine;
public class VirusSpawner : MonoBehaviour
{
[SerializeField]
private int objectSpawnCount = 5;
[SerializeField]
private GameObject[] prefabArray;
private void Awake()
{
for (int i = 0; i < objectSpawnCount; ++i)
{
int index = Random.Range(0, prefabArray.Length);
float x = Random.Range(-3, 3);
float y = Random.Range(-4, 4);
Vector3 position = new Vector3(x, y, 0);
Instantiate(prefabArray[index], position, Quaternion.identity);
}
}
}
As I understood what you need is a script for your objects, responsible for moving them and controlling all this "Normal" and "Virus" states.
2.1. Create a C# Script (i.e. "Virus") that moves the object as soon as it exists.
2.2. Right after instantiating your prefabs add this script to it:
GameObject newGO = Instantiate(prefabArray[index], position, Quaternion.identity);
newGO.AddComponent<Virus>();
On the new "Virus" script, add the collision detection and variable that holds the state of Normal or Virus
As #Caio Rocha said you can instantiate new Virus Object and add component to it but there can be one more way which can be faster :
Create a Empty Game Object.
Add both (Virus and Normal) prefabs as children of that prefab and drag and drop to project window to create new Prefab.
Attach this script to Parent:
public class ParentObject : MonoBehaviour
{
public GameObject VirusObject;
public GameObject NormalObject;
private bool isVirus;
private void Awake()
{
isVirus = (Random.Range(0, 2) == 1); //Randomly Make an object
//virus or normal on instantiation
if (isVirus)
{
TurnToVirus();
}
else
{
TurntoNormal();
}
}
private void OnCollisionEnter(Collision other)
{
ParentObject coll =
other.collider.gameObject.GetComponent<ParentObject>();
if (coll && coll.isVirus) //if other object is virus
{
TurnToVirus();
}
}
private void TurnToVirus()
{
VirusObject.SetActive(true);
NormalObject.SetActive(false);
}
private void TurntoNormal()
{
VirusObject.SetActive(false);
NormalObject.SetActive(true);
}
}
Now Inside prefab array move this Parent prefab instead of your own prefabs and it will randomly create normal and virus objects and when they interact normal turn to viruses. Make sure this script and collider is now on parent. This is much optimized over adding component individually just for single check.

Algorithm about playing animations of multiple objects

I'm currently working on a project that instantiates 3d models on my scene and allows the user to play their animation on button click. However, in my current code, it only plays the animation of the first object it detects even tho there are other objects around. I want to play the animation of all objects on the scene. This is part of my current code. This is the method that will fire up once the button is clicked.
public void PlayAnimation()
{
if (GameObject.FindGameObjectWithTag ("3DObject).name.Contains ("Spidey"))
{
int spideyAnimation = Random.Range(0, spideyAnimations.Length);
GameObject.FindGameObjectWithTag ("3DObject").GetComponent<Animation> ().Play (spideyAnimations[spideyAnimation]);
}
if (GameObject.FindGameObjectWithTag ("3DObject").name.Contains("Dino"))
{
int dinoAnimation = Random.Range(0, dinoAnimations.Length);
GameObject.FindGameObjectWithTag ("3DObject").GetComponent<Animation> ().Play (dinoAnimations[dinoAnimation]);
}
}
You can try something like this:
var arr = GameObject.FindGameObjectsWithTag ("3DObject");
foreach (var o in arr) {
if (o.name.Contains ("Spidey")) {
// play spideyAnimation
} else if (o.name.Contains ("Dino")) {
// play dino animation
}
}
Your current code will only find the first object, because you're calling GameObject.FindGameObjectWithTag and not GameObject.FindGameObjectsWithTag
UnityDocs - GameObject.FindGameObjectsWithTag

unity object reset button and slider

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.

I have two 3dtext, one plays the animation, the other reverses it. After one go, the animation wont play anymore, why?

I have a 3dtext named Play, which when clicked will play the animation; the other one is named Back, which reverses the animation. Problem is after I Played and Backed it, the animation wont play anymore when i clicked Play.
The animation named redsubmenu is in legacy and clamp forever wrap mode.
public class PlayButtonScript : MonoBehaviour {
//public static PlayButtonScript pbs;
public GameObject redsubmenu;
void Update(){
#if UNITY_EDITOR
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Input.GetMouseButtonDown(0)&&Physics.Raycast(ray,out hit)){
if(hit.collider.name == "Play"){
redsubmenu.animation.Play();
}
}
#endif
}
}
public class BackButtonScript : MonoBehaviour {
// Update is called once per frame
void Update () {
#if UNITY_EDITOR
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Input.GetMouseButtonDown(0)&&Physics.Raycast(ray, out hit)){
if(hit.collider.name == "Back"){
transform.parent.animation["redsubmenu"].speed = -1;
transform.parent.animation.Play("redsubmenu");
}
}
#endif
}
}
It appears that you never reset the speed of the animation back to 1. When you click play the first time the speed is initially 1, so it works fine. However, when you back you set the speed to -1 and it is never set to any other value.
Try using:
if (hit.collider.name == "Play") {
transform.parent.animation["redsubmenu"].speed = 1;
redsubmenu.animation.Play();
}
in your play button script.
You might also be able to make use of Animation.Rewind.
http://docs.unity3d.com/ScriptReference/Animation.Rewind.html
Just to be more specific, i edited my playbuttonscript as shown below:
if(Input.GetMouseButtonDown(0)&&Physics.Raycast(ray,out hit)){
if(hit.collider.name == "Play"){
if(redsubmenu.animation["redsubmenu"].speed == -1){
redsubmenu.animation["redsubmenu"].speed = 1;
} else {
redsubmenu.animation.Play();
}
}
}
in my back button, i delete the transform.parent.animation.Play, no need for that.

How to Work With GUI button in unity

I want to get user input through GUI Button in unity3d unityscript. I have write this script to get user input through keyboard
var f_hor : float = Input.GetAxis("Horizontal");
//Get Vertical move - move forward or backward
var f_ver : float = Input.GetAxis("Vertical");
if (f_ver < 0) {
b_isBackward = true;
} else {
b_isBackward = false;
}
its work fine and its give me 0 and 1 accordingly..But i want the same action through GUI button.Like if i have four GUI button..and they work same as this did...I can make GUI button in ONGUI function..But how can i achieve this functionaility...Any help
Altough I don't know if it is the best way to go (Unity's gui element are not the best for ingame HUD or menu), this should do the job:
private bool buttonPressed = false;
public void Update()
{
if (buttonPressed)
{
//do what you want
buttonPressed = false;
}
}
Sorry for using C# code, but I don't know JS. It should be easy to translate tough.
public void OnGui()
{
Rect rect = new Rect(...); //your button dimension
if (GUI.Button(rect, "AButton")
{
buttonPressed = true;
}
}
EDIT:
If you want to manually handle input from mouse you can use methods of MonoBehavior such as OnMouseDown or OnMouseUp.
Alternatively you can check from inside Update if a mouse event occured, have a look at Input.GetMouseButton or similar methods of Input class.

Resources