Unity3D Particle Playground 3.0.3 AddNode issue - unity3d

I use Particle Playground 3.0.3 in Unity3d 5.4.1f1 on Windows 10 to make spline of particles. I need to add and remove node interactively. When I try do this through script — nodes add and remove but particles stop to move after 1-2 (rarely more) iterations.
The code is simple:
// ================================================
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
AddNewPoint();
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
RemoveLastPoint();
}
}
// ================================================
public void AddNewPoint()
{
Debug.Log("Add at " + spline.NodeCount);
spline.AddNode(spline.NodeCount);
}
// ================================================
public void RemoveLastPoint()
{
spline.RemoveLast();
Debug.Log("Removed, size is " + spline.NodeCount);
}
I also checked that the same problem happens when I add/remove nodes by Playground Spline component in Editor. But as I see there's no such problem when I make a long delay (about 5-10 seconds) between two additions or removals.
Does anyone knows what happens? Also, screenshots:
initial state, particles move http://take.ms/xUWBPH
after several nodes added particles die http://take.ms/Y7a16

Related

How to make Trajectory Predictor on my ball?

hey guys , So as you can see i made a robot arm grab a slingshot's objectholder with a ball in it. My arm pulls it any direction I want it but I wanted the user to know which box is going to be shot at.
If you're applying an impulse force (or velocity) to your ball and there is gravity in your world, your item will follow the Projectile motion;
Here you can find details about it:
https://en.wikipedia.org/wiki/Projectile_motion
There are basically two main options
calculating it yourself
This is probably way better for performance especially if you want a really simple trajectory preview without accounting for any collision etc
refer to linked article. But it basically comes down to
and would need slightly rework from 2D to 3D physics, should be trivial though since the important part about the Y axis basically stays the same.
You would
Call this simulation with according supposed shoot direction and velocity
Visualize the tracked positions e.g. in a LineRenderer
Physics.Simulate
This allows you to run physics updates manually all within a single frame and actually let the Physics engine handle it all for you
This costs of course a lot of performance but you get all collisions etc accounted for automatically without getting a headache
You would
Make a snapshot of all Rigid bodies in your scene - in order to reset after the simulation
Simulate the desired amount of physics steps (XY seconds ahead) while keeping track of the simulated data
reset everything to the state tracked in step 1
use the simulated data from step 2 to visualize e.g. with a LineRenderer
This might look somewhat like e.g.
public class Prediction : MonoBehaviour
{
public LineRenderer line;
public Rigidbody tracked;
private Rigidbody[] allRigidbodies;
private void Awake()
{
allRigidbodies = FindObjectsOfType<Rigidbody>();
}
private void LateUpdate()
{
// Wherever you would get this from
Vector3 wouldApplyForce;
// Step 1 - snapshot
// For simplicity reasons for now just the positions
// using some Linq magic
var originalPositions = allRigidbodies.ToDictionary(item => item, item => item.position);
// Step 2 - Simulate e.g. 2 seconds ahead
var trackedPositions = new Vector3 [(int) (2 / Time.fixedDeltaTime)];
Physics.autoSimulation = false;
tracked.AddForce(wouldApplyForce);
for(var i = 0; i < trackedPositions.Length; i++)
{
Physics.Simulate(Time.fixedDeltaTime);
trackedPositions[i] = tracked.position;
}
// Step 3 - reset
foreach (var kvp in originalPositions)
{
kvp.Key.position = kvp.Value;
}
Physics.autoSimulate = true;
// Step 4 - Visualize
line.positionCount = trackedPositions.Length;
line.SetPositions(trackedPositions);
}
}
Of course we won't talk about performance here ^^

Unity game stops while coroutine running

Unity(character movement and everything in current game scene) stops while downloading textures from web url.
I'm using Socket.IO for online multiplayer.
request 'map info' with socket.emit in void Start()
get 'map info' and create map entities with Instantiate()
get profile images(textures) from url and change texture of map entities
IEnumerator DownloadImage(string MediaUrl, SpriteRenderer spr) {
// check if url is malformed
if (MediaUrl == null || MediaUrl.Contains("Null")) {
yield break;
}
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.DataProcessingError || request.result == UnityWebRequest.Result.ProtocolError)
Debug.Log(request.error);
else {
Texture2D tex = ((DownloadHandlerTexture)request.downloadHandler).texture;
spr.sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), tex.width / 2f);
}
}
Is there a way to keep game running with user interactions(character movement or button actions) while downloading textures?
Unity co-routines (CR) are a entry-level and sometimes hazardous form of performing work over a series of frames on the Main Unity thread. They are useful for what is essentially a logical lerp across a series of frames such as fading, explode-my-spaceship-after-5-seconds, or deferring cockpit display updates.
CRs are sliced up and multiplexed over the Main Thread so the slowest part of your game is going to be the CR with the largest demand for time in a single frame. Performing anything lengthy during a single yield per frame is going to slow down your game, particularly I/O operations.
Alternative - Unity Jobs
Instead, consider using Unity 'IJob' which allows for operations to be executed on a worker thread thus freeing up the Unity thread to do what it does best and not lengthy I/O operations.
Unity:
Use IJob to schedule a single job that runs in parallel to other jobs and the main thread. When a job is scheduled, the job's Execute method is invoked on a worker thread. More...
Now wasting a whole thread that may spend it's life waiting for I/O to complete is arguably a waste of a perfectly good thread but it is certainly better than blocking the Main Thread.
Coroutines...thar be dragons
So earlier I mentioned "hazardous" with regards to CRs and the reason is three-fold:
When firing off a CR in a method that is called many times per second such as Update() make sure you adequately guard the StartCoroutine() else you could end up with zillions of them running only to run out of memory. This one is quite common on Stack Overflow
Don't make the mistake of thinking they are somehow a worker thread or other piece of magic that won't slow down the Main Thread
In many ways CRs are like DoEvents, Application.DoEvents in Visual Basic and .NET respectively and both leads to a nasty case of re-entrancy (where state is clobbered and unpredictable just like in a multi-threaded app but without the threads)
There's also the whole is Unity promoting a strange use of IEnumerator and yield? debate.
My other tip is, if you need something lerped or delayed and isn't doing I/O, consider just making a class and use Time.
e.g. in my flight sim, I only want to update cockpit displays every 100ms or so. For that I define a Delay class:
public class Delay
{
private float _lastInterval;
/// <summary>
/// The timeout in seconds
/// </summary>
/// <param name="timeout"></param>
private Delay(float timeout)
{
Timeout = timeout;
_lastInterval = Time.time;
}
public float Timeout { get; }
public bool IsTimedOut => Time.time> _lastInterval + Timeout;
public void Reset()
{
_lastInterval = Time.time;
}
public static Delay StartNew(float delayInSeconds)
{
return new Delay(delayInSeconds);
}
}
.
.
.
private void Update()
{
if (!_delay.IsTimedOut)
{
return;
}
// Do something time consuming
_delay.Reset();
}

Unity: Weird scene transition bug after adding a "Persistent-Scene" with a GameManager

I made a pretty basic 2D game to learn. I have 2 Scenes, and switching between them worked great. I used empty gameObjects as Start/Exit point of the Scene, so that the game would know to put player on point X after exiting through point X (for example exit outside house if I walk out the door).
Then I added a "Scene0", to use for persistent general scripts like GameManager, Sounds, Music, etc. With just one object called "Controller" that I DontDestroyOnLoad().
After adding this Scene and then just switching Scenes right away to my MainScene, all of a sudden the game starts acting really strange;
the first time I move from my MainScene (Scene1), to my secondary Scene (Scene2), it works fine, but then when I leave Scene2 to go back to Scene1, the player spawns in the middle of nowhere.
And this ONLY happens if I launch the game from my Persistent Scene.
I have no idea what is wrong, I don't add anything that interferes with my scene transitions, all I've added so far is playerHealth, for testing.
Scripts attached to my (persistent) Controller:
DDOL:
public class DDOL : MonoBehaviour {
// Use this for initialization
void Awake () {
DontDestroyOnLoad (gameObject);
}
}
GameManager:
public class GameManager : MonoBehaviour {
public static GameManager manager;
public int playerMaxHealth;
public int playerCurrentHealth;
void Awake(){
if (manager == null) {
manager = this;
} else if (manager != this) {
Destroy (gameObject);
}
}
// Use this for initialization
void Start () {
SceneManager.LoadScene("test_scene");
}
// Update is called once per frame
void Update () {
}
}
Scripts attached to my StartPoint:
PlayerStartPoint:
public class PlayerStartPoint : MonoBehaviour {
private PlayerController thePlayer;
private CameraController theCamera;
public Vector2 startDir;
public string pointName;
// Use this for initialization
void Start () {
thePlayer = FindObjectOfType<PlayerController> ();
if (thePlayer.startPoint == pointName) {
thePlayer.transform.position = transform.position;
thePlayer.lastMove = startDir;
theCamera = FindObjectOfType<CameraController> ();
theCamera.transform.position = new Vector3(transform.position.x, transform.position.y, theCamera.transform.position.z);
}
}
}
And finally ExitPoint:
LoadNewArea:
public class LoadNewArea : MonoBehaviour {
public string levelToLoad;
public string exitPoint;
private PlayerController thePlayer;
// Use this for initialization
void Start () {
thePlayer = FindObjectOfType<PlayerController> ();
}
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.name == "Player")
{
SceneManager.LoadScene(levelToLoad);
thePlayer.startPoint = exitPoint;
}
}
}
EDIT:
After moving all my DDOL gameObject to the Pre-Scene, it worked. So, I can assume the fault is inside Player or Cameras Start() functions since when they start in Scene1 they get called every time I enter the Scene (only DDOL).
I tried adjusting their Start()functions like follows:
Original camera:
void Start () {
Debug.Log("Starting camera");
if (!cameraExists) {
cameraExists = true;
DontDestroyOnLoad (gameObject);}
else{
Destroy (gameObject);
}
}
Changed Camera:
void Start () {
DontDestroyOnLoad (gameObject);
}
The exact same changes was made in Player.
Obviously this doesnt work because it creates a new Camera/Player every time I enter Scene1 (btw why does it not try to create them when I enter Scene2?, is it because they start in Scene1?). HOWEVER, the new player/camera do start at the correct position, and if I zoom out I can see the old player/camera at that same wrong position as before. So something weird happens when their Start() is called a second time it seems.
You've now mentioned that you had code something like this,
void Start () {
Debug.Log("Starting camera");
if (!cameraExists) {
cameraExists = true;
DontDestroyOnLoad (gameObject);}
else{
Destroy (gameObject);
}
}
Note that this is unfortunately just "utterly incorrect", heh :)
The issues you mention in the question (preload scenes etc) are just totally unrelated to the problem here.
In Unity if you have a character C that persists between scenes a, b, c as you load those scenes, you must kick-off C in it's own (perhaps otherwise empty) scene, you can not use "a" as a matter of convenience to kick off C.
The pattern is, in each of a, b, c just have a line of code like p = FindObjectOfType<Player>(); which runs when the scene loads, and position C as you wish.
Now, regarding your specific puzzle about the unusual behavior you are seeing.
I understand that you want to know why you are observing what you do.
It is a combination of confusion over the following issues: 1 - difference between Awake and Start, 2 - confusion over script execution order {but see below1} 3 - confusion about Destroy versus DestroyImmediate 4 - Not using Debug.Log enough, and not using gameObject.name in there (it's a common in Unity to be wildly confused about which object is talking in Debug.Log) 5 - where you mention you see the other object "off to the side", it's common to drastically confuse which one is which in such situations 6 - confusion between the computer programming concept of "instantiation" (ie, of a class or object) and "instantiating" (confusingly, it's the same word - utterly unrelated) game objects in nity.
If you fiddle around with all those issues, you'll discover an explanation for the behavior you're seeing!
But it doesn't amount to much; in Unity in the "C .. a b c" example you have to create C separately beforehand.
1 {aside, never fiddle with the script execution ordering system in Unity in an effort to solve problems; it's only there for R&D purposes; however it could in fact help you investigate the behavior at hand in this problem, if you are particularly keen to fully understand why you're seeing what you're apparently seeing}
Use the debugger. Have breakpoints at the relevant spots, like PlayerStartPoint.Start() and LoadNewArea.OnTriggerEnter2D() and check that they are executed
At the right time
The right number of times
With the expected values
This should make you see where things get out of hand.
If you use Visual Studio, install https://marketplace.visualstudio.com/items?itemName=SebastienLebreton.VisualStudio2015ToolsforUnity to be able to debug Unity from within Visual Studio.
If you are not using Visual Studio, you probably should.
Is player persistent between scenes (does he have DontDestroyOnLoad)? If no then this might be the reason - you can either try loading the scenes by using the additive mode or by instantiating the player on scene load in correct position.

Photon Unity3d: OnPhotonSerializeView() doesn't work

I'm working in a car game with multiplayer.
All works fine, master and clients are connected to the room fine. (I have been using Marco Polo tutorial)
The problem is when I see other cars moving in the screen, the position updates by teleporting the cars. Appears and disappears all the time.
Part of my code:
PhotonNetwork.automaticallySyncScene = false;
public class CNPlayerManager : Photon.MonoBehaviour
{
...
void FixedUpdate()
{
if (photonView.isMine)
{
//it works fine
}
else
{
transform.position= Vector3.Lerp(transform.position, this.correctPosition, Time.deltaTime * 5);
transform.rotation= Quaternion.Lerp(transform.rotation, this.correctRotation, Time.deltaTime * 5);
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(transform.position);
stream.SendNext(transform.rotation);
}
else
{
this.correctPosition = (Vector3)stream.ReceiveNext(); //Line 100
this.correctRotation = (Quaternion)stream.ReceiveNext(); //Line 101
}
}
My PhotonView in my car prefab is like this:
(source: photonengine.com)
but in my Photon Version I have more options. In Owner I have "set at runtime" and "Fixed". And in "Observed components" I have 2 components, my car prefab and the script CNPlayerManager.
When I playing with 2 cars, In the first car I sometimes get this error: "IndexOutOfRangeException: Array index is out of range. PhotonStream.ReceiveNext ()..." In the line 100.
In the second car I get the same.
Could you help me please?
what do you mean when you say that you "observe the car prefab"? I think it is enough to just observe the CNPlayerManager script in this case since it handles the position and rotation synchronization.
However I would like to recommend you taking a look at the scripts the PUN package already contains, especially the PhotonTransformView script. This one does what you want to achieve and also provides some synchronization options you can check and see which one fits your needs best.
Please let us know if you still run into problems.

OnTriggerExit not triggering in Unity

I'm currently working on an exam project, where I'm using TUIO as an input device for my Unity setup. The idea is to use fiducials to create various inputs (in this case the values 1 though 6, to simulate an ordinary six-sided die), that will then be registered within Unity. OnTriggerEnter works fine with my current setup, correctly changing the color of tiles based on the 1-6 input. OnTriggerExit however, which is supposed to change the tile color to white when the tiles are not being triggered, never triggers. The problem seems to be that the TUIO setup creates clones of the in-engine prefabs, which disappear after the corresponding input device is removed. Thus, Unity doesn't register that the trigger "exits" as it should, since the object simply just disappears entirely. I have tried countless solutions, but none have worked so far.
Here is the code I have been using for my triggers.
function Start () {
}
function Update () {
}
function OnTriggerEnter (other: Collider) {
if (other.CompareTag("Player")) {
renderer.material.color = Color.red;
}
}
function OnTriggerExit (other: Collider) {
if (other.CompareTag("Player")) {
renderer.material.color = Color.white;
}
}