Unity script stops working when scene is reloaded - unity3d

I am trying to create an infinite runner.
My scene have a "road creator" object that is just a trigger and a script attached to my road prefab.
Every time a piece of road leaves the road creator trigger, a new piece of road is created.
Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class roadGenerator : MonoBehaviour
{
public GameObject road;
private void OnTriggerExit(Collider other) {
if(other.gameObject.tag == "roadGenerator"){
Instantiate(road, new Vector3(200, 0, 0), Quaternion.identity);
}
}
}
My issue is that once the player loses and the level reloads the script stops working.
Everything gets loaded properly (the trigger object and the first piece of road with the script attached) but for some reason the script doesn't get triggered...

Hey I think I'll need some more context to understand your problem:
You have a "roadGenerator" with a trigger and the Script attached + a "Road" Prefab with the Tag "roadGenerator" right?
I suppose by "realoading the level" you mean reloading the Scene with something like SceneManager.LoadScene(...)
It would also be good to know what you already tried out to fix it. :)

Related

Best practice to to access components using scripts in Unity?

I am new to Unity so go easy on me. :)
I added an game object with a text field component (via TextMeshProUGUI) to my heads up display in my scene. I want to use this to display various statistics on it for debugging purposes during game play.
I then created a script which I added as a component to the same game object that holds my text component. Is this the best practice? Not sure how else I would get the script to execute.
Once I had my script created, I needed to find the text component as well as some other components in my scene so I could display the debug information. Below you can see how I did it... it feels a little dirty to be searching the entire scene to find these things. Would love some insight on how long-time Unity programmers go about this!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerDebugStatistics:MonoBehaviour {
TextMeshProUGUI playerDebugStatisticsText;
PlayerCharacterController playerCharacterController;
Health playerHealth;
private void Start() {
// First find the object in the scene named "PlayerDebugStatisticsText" and then get it's TextMeshProUGUI component
this.playerDebugStatisticsText = GameObject.Find("PlayerDebugStatisticsText").GetComponent<TextMeshProUGUI>();
// Get the player character controller
this.playerCharacterController = GameObject.FindObjectOfType<PlayerCharacterController>();
// Get the player health from the player character controller
this.playerHealth = playerCharacterController.GetComponent<Health>();
}
void Update() {
// Update the text every frame
this.playerDebugStatisticsText.SetText(string.Format("{0:N2}", this.playerHealth.currentHealth));
}
}
3 ways
Create an inspector reference to the other object and access it from your script - a public or private (with [SerializeField]) attribute in your script - and drag the component in like in this video: https://youtu.be/dMgQOP7kdxg?t=425
Use the singleton pattern: https://www.youtube.com/watch?v=5p2JlI7PV1w
Use dependency injection - https://github.com/modesttree/Zenject
Your way isn't terrible if you don't do it in the Update() loop, and cache your objects (like it appears you are doing), but if you need that performance in Start(), the above options can help.

How to switch scenes using the OVR Utilities?

I'm trying to switch scenes when an object in a VR environment is pressed. Should be a simple line of code but when I try to execute it the game crashes. The game is build to the Oculus Go.
I know I've added the scenes to the build to that shouldn't be the problem. I also got the index of '1' right in the build settings.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SphereScript : MonoBehaviour
{
public void LoadScene()
{
SceneManager.LoadScene("1");
}
}
private void ProcessTouchpadDown()
{
if (!m_CurrentObject)
return;
Interactable interactable = m_CurrentObject.GetComponent<Interactable>();
CubeScript.onVRTriggerDown();
SphereScript.LoadScene();
}
}
There seems to be a small mistake in SceneManager.LoadScene("1");. If you want to load a scene by its built number and not by its name, you'll have to put in an integer and not a string. So unless your scene is named "1", this won't do the trick. Try SceneManager.LoadScene(1); instead.

UNITY 2D - Can't change Child's position

I have created a project and put a character in it, a Ninja. I drew every part of his body and put them together into one organized gameObject. It is organized as this.
Ninja Organization
NOTE : The Left_Arm GameObject has a parent so it can be rotated by the shoulder like a real arm
Now here comes the problem. I've searched and searched for hours and haven't found a solution to something that is surely so simple and dumb. In a script, I try to move the Left_Arm parent for a little animation. Here's the script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NinjaShooting : MonoBehaviour {
[Header("GameObjects")]
public Transform leftArm;
public Transform rightArm;
[Header("Other")]
public bool shooting = false;
// Update is called once per frame
void Update () {
Debug.Log(leftArm.localPosition);
leftArm.localPosition = new Vector3(100, 100, 100);
Debug.Log(leftArm.localPosition);
shooting = false;
}
}
The public variables are all assigned and everything, there are no errors in the console, but the line leftArm.localPosition = new Vector3(100, 100, 100); doesn't seem to do a thing to my character.
Here's is the Console after running it : Image
The console seems alright. The start position is (-0.3, 0.2, 0) and after leftArm.localPosition = new Vector3(100, 100, 100); the position is debugged as (100, 100, 100) as it should be. But the position changes in the inspector, nor in the game window...
Additionnally, the starter position is debugged every frame, but it shouldn't. So I assume that my position isn't taken into account or something.
I've done this so many times, and always has worked.
I even tried with a new project and recreated it, and there, mysteriously, it worked. So there is someting wrong with my organization or something. Sorry if this is a stupid question.
Thank you in advance
PS : Here is an image of the script in the editor, just in case there something wrong with that : Image
PS : The script is a it weird because I simplified it :). But this doesn't work too
This issue is likely caused by an Animator controller "locking" properties that are not actually part of its Motion. In this case, it is "locking" the Transform's position. Unity does not report any warnings or errors when you try to modify those properties, even if they are being controlled by an animation.
The typical offender is the Write Defaults property being set to true for your Animation States in your animation controller. Have a look here at the documentation for what Write Defaults does, and it will make more sense to you. I suggest changing it to false for all animation states that do not need it.

Unity - Parent with children fall apart

I have a player character, made of some cubes, spheres and a capsule. I created the empty object Player and all body parts of the player are a child of Player. I have two planes, with a moving platform in between. I can walk and jump on the normal planes and the walls, but when the player is on the moving platform the bodyparts of the player fall apart. Maybe it's something really stupid, but I just started with Unity.
This is what goes wrong, the player falls apart on the moving platform: http://nl.tinypic.com/r/207s3sz/9
And below the information about the overview, the player, the body parts, and the moving platform with according character-holder. All bodyparts have the same properties as the body part on the screenshot. Can anyone help me with what goes wrong here? How can I transport the whole player by the moving platform?
HoldCharacter script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoldCharacter : MonoBehaviour {
void OnTriggerEnter(Collider other) {
other.transform.parent = gameObject.transform;
}
void OnTriggerExit(Collider other)
{
other.transform.parent = null;
}
}
You just need to disable the isTrigger flag. Here are some insights
so how Is Trigger works is that... it will fire OnTriggerExit and OnTriggerEnter, but it will let the object go through it. If you disable the IsTrigger, then you need to move the logic to OnCollisionEnter on OnCollisionExit methods. If the isTrigger uncheck kind of worked, maybe is just the fact that you move the logic for HoldCharacter to OnCollisionEnter and OnCollisionEnd respectively Like this:
void OnCollisionEnter(Collision collisionInfo) {
collisionInfo.gameObject.transform.parent = gameObject.transform;
}
void OnCollisionExit(Collision collisionInfo) {
collisionInfo.gameObject.transform.parent = null;
}
Regards
If I'm correct, the children of objects with Rigidbodys have physics as well. Maybe put the rigidbody on a child of the player, like so.
Player
-head
-arms
-legs
-empty gameobject with rigidbody

Add particles on button click in unity

I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();
I have also added particles component from unity editor..
Thanks in advance
Edit :
as #kardux suggested:
declaration :
[SerializeField] private ParticleSystem ps;
on method :
ps.Play()
Screenshot from inspector:
Error:
I/Unity (23313): NullReferenceException
I/Unity (23313): at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity (23313): at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity (23313): at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity (23313): at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661
First of all if you're using particles inside Unity UI I highly advise you looking to UIParticleSystem.cs script from Unity UI Extension repository: this is a community gathering of many useful UI tools :)
(simply don't forget to add the UI/Particles/Hidden shader that you can find here)
You can change the sprite you want to use here:
Also keep in mind when using this script that you will have to scale your particles according to your screen (particles are initialized at a size of 1 because that's 1 meter in Unity 3D world: but now you will probably be in canvas space which will be something like 1920x1080px so 1px will be very small). You can find some base settings below:
Now coming to your scrip I suspect you simply have to call Stop() before Play() like this (note I used a burst emission type in my particle system settings):
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Stop ();
ps.Play ();
P.-S. Please note that if you use UIParticleSystem script you will have to consider your particles system as an UI item (will be rendered on top of other items based on hierarchy order)
Hope this helps,
EDIT:
You have two ways of setting up your GameObjects:
you have all component on the same GameObject (ParticleSystem, UIParticleSystem and YOUR_SCRIPT): this way you can get the ParticleSystem reference by calling GetComponent<ParticleSystem>() inside your script
you have one particle GameObject (with ParticleSystem and UIParticleSystem) and YOUR_SCRIPT is on another GameObject: you can't call GetComponent<ParticleSystem>() in your script since it will search on the components of this GameObject so you declare a ParticleSystem ps; variable (either public or [SerializeField] private) that you assign through the Inspector by dragging your particle GameObject to it.
Note that implicitly, GetComponent<ParticleSystem>() equals this.gameObject.GetComponent<ParticleSystem>(): that's why it will search components from the current GameObject.
EDIT 2:
Not sure why your script throw this NullReference exception: I just tried with a very short script and it works perfectly...
public class TestScript: MonoBehaviour
{
[SerializeField]
private ParticleSystem ps;
void Start()
{
// This one is not even needed
ps.Stop();
}
public void PlayParticles()
{
ps.Stop();
ps.Play();
}
}
Provided you have a particle system on the same gameObject as the script that is calling it, it should be fine.
Are you using a UI button? If so, have a look here..
http://answers.unity3d.com/questions/852397/particle-system-in-46-ui.html
It's old but still relevant.
Are you using the New Unity UI System or GUI, Is the UI worldspace?
Create a empty gameobject - attach the particle to that.
Whenever you want emit particles call Gameobject.SetActive(true);
Make sure Play on Awake option is checked in the particle system.
Set the position of the particle according to your UI.
public GameObject particle;
//include the particle in the gameobject
void Start() {
particle.SetActive(false);
}
void button() {
particle.SetActive(true);
}
//this works.