I have a gameObject with attached animation component, and have added animationClip1.anim with it.
I have the following code
public AnimationClip anim;
void Update () {
if (Input.GetButtonUp("Fire1"))
{
GetComponent<Animation>().Play(anim.name);
}
}
from interface, i have drag and dropped animationClip1.anim to the (above public variable) of the script..
Script is attached to the object.
So when i run the game, i get this error
The animation state 'animationClip1.anim' could not be played because
it couldn't be found!
Please attach an animation clip with the name 'animationClip1.anim' or call this function only for existing
animations.
Where is the problem, why on mouse click i am getting this error.. Any Idea please ? Thanks
You can try this out
void Update () {
if (Input.GetButtonUp(0))
{
GetComponent<Animation>().Play("Animation name");
}
}
Related
I am making a little game and I want my character to disappear until you press space, but I don't want to destroy it since it has a script inside. I tried what I wrote below, but it didn't work.
void Start () {
gameObject.SetActive(false);
}
void Update () {
if (Input.GetKeyDown(Keycode.Space)) {
gameObject.SetActive(true);
}
Have any clues to fix it or replacement code?
You set the GameObject to disabled with SetActive(false). As a result, the Update() method is no longer executing. Because of this, the code that will unhide your character can never run.
There are many ways to get the behavior you want, but the simplest I can think of is this: Instead of disabling the entire gameobject, just disable the renderer (whether it's a sprite renderer or mesh renderer). This will make your character disappear, but this script will keep running.
Example:
public Renderer renderer; // drag your renderer component here in the Unity inspector
void Start ()
{
renderer.enabled = false;
}
void Update ()
{
if (Input.GetKeyDown(Keycode.Space))
renderer.enabled = true;
}
Another approach (and I think, better) is to create a child object of your character's GameObject, call it "Body", and place everything that deals with rendering your character in there. Then disable/enable that child gameobject as desired.
Using gameObject.SetActive(false) disables the gameObject and all its components, including the script you're running so it can't turn itself on if the script driving it is off.
If you add the script to a parent object of the object you're trying to disable you can get the effect you're looking for like this:
public gameObejct childObject;
void Start()
{
childObject.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown(Keycode.Space))
{
childObject.SetActive(true);
}
}
I have a problem in my project. I created an animation to open the door and made it open whenever a button was pressed. Then I copied the animation and entered its value -1 to make the door close after 2 seconds, but if the character presses the door open button again while playing the closing animation, it plays that animation and this causes a bug in the game. I apologize for telling a little complicated. I am waiting for your answers. Here is my code ->
public Text text;
public Animator anim;
private void Start()
{
text.enabled = false;
anim = GetComponent<Animator>();
}
private void Update()
{
if(text.enabled && Input.GetKeyDown(KeyCode.E))
{
anim.Play("DoorOpen");
}
}
private void OnTriggerExit(Collider other)
{
text.enabled = false;
}
private void OnTriggerEnter(Collider other)
{
text.enabled = true;
}
}
You shouldn't use the Animator Play() method and instead create parameters like a Trigger that.. well... triggers the animation.
Also, you don't say what's the error you're getting so it is hard to help you, but I guess the animation is restarting? You can set so the animations can't be transitioned to itself, so it won't restart if triggered again before finishing. Edit your AnimatorController asset, and click on the animation that shouldn't transition to itself, then uncheck where it says precisely that: "Can transition to itself". (Maybe you have to double click it, maybe you have to click on the transition, don't really remember right now, you'll figure it out :) ).
I want to do menu animation. In the animator, its contain 2 animations. One is opening animation, the other is closing animation. I set the opening animation as default state and added condition between of them. The condition is a bool type parameter. I drag the script which controls they behaviours and animator component on gameobject, but when the opening animation plays and player clicks the play button the parameter turns into true but it doesn't play.
Animator canvasAnim;
public Button lvlSelector;
Button lvlSelector_A;
// Use this for initialization
void Start () {
canvasAnim = GetComponent<Animator>();
lvlSelector_A = lvlSelector.GetComponent<Button>();
lvlSelector_A.onClick.AddListener(LevelSelector);
}
IEnumerator SlideLevelSelectMenu()
{
yield return new WaitForSeconds(1f);
SceneManager.LoadScene("LevelSelectMenu");
}
void LevelSelector()
{
canvasAnim.SetBool("clickedclose", true);
StartCoroutine(SlideLevelSelectMenu());
}
Animator:
Gameobject:
This problem occurs because of your Animator. You should call Animator on Canvas game object (Not on Menu Manager). Just change your script to this:
void Start () {
canvasAnim = GameObject.Find("Canvas").GetComponent<Animator>();
...
}
I hope it helps you.
I've been working on a simple 2D game in unity and it just has three scenes, the start scene, the game scene, and the game over scene. I want to display the score from the game in the game over screen. I created a score manager game object in the game scene that uses the DontDestroyOnLoad() function to carry it over into the game over screen and I gave it access to the score which is managed by the game manager. I've been debugging my code and the score is translated over into the score manager and is maintained when the game over screen loads, but for some reason it won't let me update the score text object. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static ScoreManager Instance;
private GameController gameController;
private int scoreInstance;
private Text scoreText;
// When scene is first loaded
void Awake() {
this.InstantiateController();
}
// Use this for initialization
void Start () {
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
GameObject scoreTextObject = GameObject.FindWithTag("ScoreText");
if (scoreTextObject != null)
{
scoreText = scoreTextObject.GetComponent<Text>();
}
scoreInstance = 0;
scoreText.text = "";
}
// Update is called once per frame
void Update () {
scoreInstance = gameController.score;
Debug.Log("Score: " + scoreInstance.ToString());
scoreText.text = scoreInstance.ToString();
}
private void InstantiateController ()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if (this != Instance)
{
Destroy(this.gameObject);
}
}
}
So I tried to programmatically gather the "score text" ui component in the start function because I figured I can't just make it public and drag in the text component because the score manager is actually in a different scene than the score text object. I also tried adding this whole bit of code to gather the text component into the update function so that it can do that when the score manager is actually a part of game over screen. Nothing seems to work and I have no idea why. Can anybody please help me with this? Also I keep getting a "NullReferenceException: Object reference not set to an instance of an object" error. Thanks in advance for any help.
Unity Start function is only called the first time the script is enabled, i.e. not every time the scene changes for a DontDestroyOnLoad object.
So if you need to wire up some changes after a scene change, you need to either detect the scene change, or have an object that starts in that scene trigger the code you want to run.
Having another object on the new scene trigger things is easy and pretty fool-proof, but there's a builtin function you can add to your other objects:
void OnLevelWasLoaded(int currentLevel)
{
}
This will be called on level changes, and give you the level's number (not name sadly). However, the above is deprecated and they want you to use Unity's SceneManager, so the proper way to set this up is now:
Unity 5 OnLevelWasLoaded?
Start()
{
SceneManager.sceneLoaded += this.OnLoadCallback;
}
void OnLoadCallback(Scene scene, LoadSceneMode sceneMode)
{
// you can query the name of the loaded scene here
}
I have been having difficulty getting my movie to start playing once a certain button is hit. I can get it to work with void Start() but then the video starts playing as soon as the scene is loaded which I don't want. I have tried this for when the button is pressed to start playing the movie.
public MovieTexture myMovie;
public RawImage myLayer;
private new AudioSource audio;
public void onClick()
{
GetComponent<RawImage>().texture = myMovie as MovieTexture;
audio = GetComponent<AudioSource> ();
audio.clip = myMovie.audioClip;
myMovie.Play ();
audio.Play ();
}
The movie will show but not actually play. I'm sure I'm missing something obvious but as I am a noob at coding I can't figure out what it is. Any help would be greatly appreciated!
Make a custom method which will contain
void Play()
{
myMovie.Play ();
audio.Play ();
}
and assign it to the button component in the inspector
EDIT:
I meant, don't use onClick as you use Start etc, it's not executable like that. There are 2 ways:
1) You make a custom method (called whetever you want) e.g as I listed above and assign it to the onClick field in the inspector, press +, add a script and select a method from that script;
2)
public Button yourButton;
void Start () {
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){
Debug.Log ("You have clicked the button!");
}
like in the reference: docs.unity3d.com/ScriptReference/UI.Button-onClick.html
You can add a Video Player using Create -> Video -> Video Player
Set video player video clip, Render Mode as Camera Far Plane and Select camera as Main Camera
Create script as given below. Just call the playMovie() method in any button event