playing particle system in Unity - unity3d

I am using Unity3D to develop for the HTV Vive using SteamVR. I have downloaded an asset from the asset store with explosion effect created using a particle system. I want to play the particle animation when an object is destroyed. Here is the code I am, unsuccessfully, using.
private void OnDestroy() {
explosion.GetComponent<ParticleSystem>().Play();
}
Explosion is a public variable of type GameObject set from the inspector. I drop the particle system object there.
Why is it not working? anyone a good recommendation on a short tutorial to learn to use (not to create) particle effects?
Thanks
view of the hierarchy
I have tried this with the PS as a child of the target and as an independent object.
view of the inspector (Target)
view of the inspector (particle system)
edit: for some reason, the particle effect is destroyed right after the scene starts.

Try making the explosion effect into a prefab and instantiate it when destroyed.
GameObject explosion; // Prefab asset
private void OnDestroy() {
Instantiate(explosion, transform.position, Quaternion.identity);
}
Also, don't forget the stop action to Destroy.

Related

Attaching prefab's script to another prefab as a component

I have Player prefab with script Player
Also I have GameController prefab with script TouchMove.
This is TouchMove code:
public class TouchMove{
[SerializeField] Player player;
.....
}
So TouchMove has player object as a component, which I attach through unity inspector.
TouchMove script is responsible for player movement. That is why it neads the player object.
Also I have a lot of scenes and each one contains GameController and Player objects.
When I modify the GameController or Player components I wanted the all game objects at the all scenes to be updated. That is why I decided to create prefabs: GameController prefab and Player prefab.
In inspector I added Player prefab to GameController prefab because TouchMove of GameController requares player object.
But after it when I run the game the player script gets not active. I mean that I get unable to move player in the game. (the player script gets not working)
This problem solves if I attach Player to GameController as just game objects (not the prefabs or without prefabs)
So, my questions:
why player scripts gets not working if I attach it with prefabs and it works if I attach just as game objects (without prefabs)
Is it possible to link two prefabs in the way I described?
The reason you are getting this problem is that player prefab and specific instance of the player prefab - are not the same object. They are both GameObject-s, and can both be referenced.
In your case GameController references a player prefab, but the player in the scene is a new object, which was created on scene start by CLONING the player prefab. Since it was created only on scene start - another prefab can never reference it.
To solve this, you can take couple approaches.
First, parent both player and game controller under 1 new object, call it GameManager for example. Then you will have only one prefab - game manager, that contains both player and controller.
Second option, the one I usually use, is to find the player object at load time. Instead of passing player s a public argument, find it on awake, for example like this:
private Player player;
void Awake() {
player = FindObjectOfType<Player>();
Assert.IsNotNull(player);
}
Prefabs need to exist (be instantiated) in scenes to function, what you're attempting to do is a workflow of scriptable objects.
Instead of attaching a source prefab from your project directories through the inspector, try looking for an existing instance of the prefab in the scene (at runtime).
private void Awake()
{
player = FindObjectOfType<Player>();
}

Unity, keep playing music on different scenes

So I've been looking around and no solution seems to work to me...
I want to play some background music in all the scenes without resetting the audio.
I've a prefab with an audio source and a scritp.
the script does:
private void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("BGAudio");
if (objs.Length > 1)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
So I also tagged the prefab with BGAudio but when i change the scene it stops the music. If i add the prefab to both scenes it starts from 0..
I tried also doing a singleton but that doesn't work either.
I'm using unity 2019
I'm using an android build which i doesn't think it changes anything but just in case.
Just found out that DontDestroyOnLoad only works for objects on the root. While my Bgsound was inside a bg empty object.
You can also create a brand new scene that only includes your BGAudio object. Load both your BGAudio scene and play scene as additive.
For example: create a BGSound scene. Then create an empty gameobject called BGSoundManager. Also create your BGSound object. Then add a BGSoundManager script to your BGSoundManager gameobject and edit it like that :
private IEnumerator Start()
{
yield return SceneManager.LoadSceneAsync("BGSound", LoadSceneMode.Additive);
yield return SceneManager.LoadSceneAsync("Level1", LoadSceneMode.Additive);
Destroy(gameObject);
}

There is no reason for this Unity script to make the sprite move, yet it moves

Here's the code:
using UnityEngine;
public class playerMovement : MonoBehaviour {
public Rigidbody2D rb;
public float strength = 100f;
void Start () {
//Initialize the body of the sprite so that forces
//can be applied.
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
//Note2Self: var says this is a variable of unspecified type.
var touch = new Touch();
/*
if (touch.phase == TouchPhase.Began){
rb.AddForce(transform.forward * strength);
}*/
if (Input.anyKey)
rb.position.Set(0, 100);
}
}
I was trying to practice some basic stuff in Unity (I am not used to programming in IDE's at all, we've just used vim in my program so far) when I happened upon this oddity.
First, I didn't understand why the sprite would move at all when there can't be a touch identification, since I haven't actually tested this on a mobile device. So I commented it out and for some reason the sprite still moves. That code shouldn't be doing anything, yet it is.
I have checked to see if the sprite is using the up-to-date script - it is - and I have checked if the script is targeting the correct rigid body and that it is a rigidbody2D. It is.
What is going on?
If it is just falling it is probably effected by gravity.
You can turn this off in your script by adding rb.gravityScale = 0; at the end of your Start() function
OR
by setting it in the editor inside the rigid body component
I looked in the unity documentation:
https://docs.unity3d.com/ScriptReference/Rigidbody2D.html
which says that applying a Rigidbody2D component to an object will place it under control of the physics engine.
The Rigidbody2D class essentially provides the same functionality in 2D that the Rigidbody class provides in 3D. Adding a Rigidbody2D component to a sprite puts it under the control of the physics engine. By itself, this means that the sprite will be affected by gravity and can be controlled from scripts using forces.
I have run into issues with rigidbodies on more than one occasion, I suggest you check the RigidBody2D component in the unity inspector window and make sure to uncheck use gravity.
Also, you may want to just write a custom script without using a rigidbody. Doing a search on youtube will probably give you exactly what you need for that. Hope this helps!

Camera rotation within a prefab

I am trying to create a multiplayer game in unity3d using a diablo like camera system. So wherever I click on the screen. The system it was working fine in singleplayer where I did not need to include a camera in a player prefab. However Now I am facing the problem where my camera rotation is also affected by the rotation of my prefab parent. The hierarchy looks like this:
There is a script added to the camera that looks like this:
using UnityEngine;
using System.Collections;
public class MainCameraComponent : MonoBehaviour {
public GameObject Reaper;
private Vector3 offset;
void Start () {
offset = transform.position - Reaper.transform.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = Reaper.transform.position + offset;
}
}
When I run the game the camera always stays behind my character, while I want it to always stay at the same rotation. so if I order my character to walk north I would see his back, if it would walk south I wanted to see the front.
notice how the shadow changes, (thus the rotation) but i always face the back of my model. TLDR: I want my child camera to ignore the rotational change of its parent and be static. whilst letting my camera position be guided by its parent. as far as I know it seems impossible to make a networkmanager instantiate a new player prefab and attach a camera afterwards on the same hierarchy level.
Any help would be greatly appreciated.
However Now I am facing the problem where my camera rotation is also
affected by the rotation of my prefab parent
That's because your Camera is a child of the player so it will do whatever the Player/parent is doing.
Your camera should not be under the player. Remove it and make sure it is not a child of the Player or any other Object. That script should work or make the camera follow the player without making the Camera the child of the GameObject.
Remove Player = GameObject.Find ("Player"); from the LateUpdate function. You have already done this in the Start function, so it is unnecessary to do it in the LateUpdate function. GameObject.Find ("Player"); should never be called directly from the LateUpdate function. It will slow down your game.
EDIT:
After reading your comment, it looks like you want to instantiate a player with the camera. You can do this without making the camera a child of your player.
Your current Setup:
Player
Model
Projectile
Projectile Mesh
Camera
So your camera is under Player.
You new Setup:
PlayerPrefab
Player
Model
Projectile
Projectile Mesh
Camera (Attach script in question to this)
Camera is now PlayerPrefab instead of Player. Now, you can instantiate PlayerPrefab and move the Player with a script. I don't know what your move script looks like but it should be attached to the Player not PlayerPrefab. The PlayerPrefab is used to hold everything so that it can be easily instantiated as one. The code in your question should be attached to your Camera.

Particle at Input.mousePosition Point

I am trying to understand this link which, I believe, is supposed to create a particle where you left-click your mouse. Am I correct?
I have attached the script to an empty game object, so it runs when I run my Unity project. I added a new Particle System game object and dragged it onto the public field of the inspector. Is this the right way of doing it, or should I assign something else to the public variable?
The particle system starts firing up as soon as I run the project, so how do I stop that and then make it begin when and where I have clicked my mouse curser?
public GameObject particle;
if ( Input.GetButtonDown("Fire1") )
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast(ray) )
Instantiate(particle, transform.position, transform.rotation);
Debug.Log(Input.mousePosition.x);
}
You should either turn off looping in the particle system or Stop() or Pause() it on Awake() in your script and Play() when clicking the fire button.
Check this page: http://docs.unity3d.com/ScriptReference/ParticleSystem.html
The sample that you have provided doesn't take a particle system, but some 'projectile' prefab, it basically spawns the prefab instance when you click mouse button. It is just an example of very very basic shooting mechanic. I believe that naming on that script could have been better. (I believe that this sample was taken from one of Unity's Merry Fragmas videos, they used some kind of particle system in a similar manner, you'll have to configure the particle system to burst a bunch of particles and not loop after that if you want to use it this way)