Loading Next Level - unity3d

I am making a game in Unity. There are currently two levels. I count to 30 seconds, when the time becomes 0, I want to load the next level automatically. But when the next level is loaded, the game screen freezes and I cannot move anything. The function I used to load the next level follows below (this function is in a script which an empty game object which will not be destroyed when loading a new level carries):
function loadNextlvl(){
var cur_level = Application.loadedLevel;
yield WaitForSeconds(5.0);
Application.LoadLevel(cur_level + 1);
}
What should I do?

My work with Unity has been hobby-driven only, but anytime I've used Application.LoadLevel I passed it a string of the level name, rather than a pointer. I see from the API that it's overloaded to take an int as well, but maybe for testing purposes, call it by name to see if that works.
Also, you need to tell Unity the levels you're going to be using. You can do this in the Build Settings off the file menu.
Lastly, you can try using Application.levelCount to see if you're within the bounds of levels.

Related

Why is "Cast to BP_Ladder" failing all the time?

I am having trouble with my Unreal Engine 4 project. I'm very new to this and i don't really understand what's going on. I have made ladder functionality so the character can climb up the ladder and stand on the Static Mesh that is on top. But when i want to go down the ladder i want to trigger the "Allow Down" function on Actor "BP_Ladder" but the cast is failing everytime. what is causing the casts to fail?
I've looked around and other people with cast failed problems have mostly had the names wrong but my ladder is called "BP_Ladder" and that is what i'm casting to so that leaves me really confused.
My BP_Dude blueprint (this is being called every tick)
My BP_Ladder blueprint (this is what i'm trying to trigger)
The goal for this function is that the collision of the static mesh will turn off and then allow me to move down the ladder like normal.
I'd really appreciate your help with this, its my first couple of days using unreal engine and the Epic Games tutorials i followed didn't show all of the blueprints so everyone was left helpless with half broken blueprints.
Understanding Casts
In its simplest form, if your Actor can be cast to BP_Ladder, then it will return the casted object on the output pin.
Just to ensure you know how a cast works, I have to point out that you can't cast a given type to some unrelated arbitrary type; it has to be "castable" to the cast destination. So if you think that the Actor object returned by your overlap is genuinely a BP_Ladder, or a blueprint class that derives from BP_Ladder, then you should be OK. But that has to be the case; otherwise it will fail every time.
https://docs.unrealengine.com/en-us/Engine/Blueprints/UserGuide/CastNodes
Sorry if I'm being patronising, but if a cast isn't working 9/10 it hasn't been used correctly.
Debugging
OK that out of the way, if you think you are genuinely casting to the correct type and it's still failing, then you'll need to debug your blueprint with the objective of finding what type is being given to the cast node which results in the failure.
Select the cast object in your blueprint.
Press F9 to create a breakpoint; a red circle should appear on the top left of your cast box
Run your game in PIE mode (Combo next to play, New Editor Window (PIE))
Put the game in a scenario where your cast will fire (I presume touch the ladder)
The breakpoint should trigger; your game window will go grey and you'll get a large red arrow pointing down towards your cast box where you placed the breakpoint
Hover over the Object pin on the input side of the cast box. It should show a alt-text containing details of the variable.
Inside the alt-text box, look for Current value; this should show you the current object type that you are about to cast. You need to ensure that this value is what you expect.
https://docs.unrealengine.com/en-US/Engine/Blueprints/UserGuide/Debugging
Example
I've taken a screenshot of a working game; in this you will see:
a Breakpoint (the red circle) is shown on the function node (the box)
the Execution node (red arrow) is Create Rolling Stock
the Current value of the variable is DepotComponent...Depot
Final thoughts
There's a couple of gotchas when using blueprints; one of them in this case could be that you can have two classes with the same name (although they might have different internal "script names" - effectively a fully qualified path). When you debugging an object variable, make sure you match the entire path to the location of your asset in your content folder; this will ensure that you are indeed attempting to cast to the object you think you really are.
Another classic gotcha is "hot reloads". Sometimes the editor needs to reload a module after an on-the-fly build but a class conflict occurs internally; this results in the new version of the class getting a different name (prefixed with HOTRELOADED). Watch out for this; it can cause you to be dealing with two distinct types when casting and you don't even realise. A real sanity-sapper. If in doubt, close and re-open the editor; it fixes it every time.
On Begin Overlap is only triggered when you START an overlap, so if you have some logic that sets your "can climb" to false you will need to move outside of the collider and back into it again for another Begin Overlap event.

How do you restart Swift Command Line code from the beginning?

I am new to swift and I am currently trying to build a basic number
guessing game using Xcode's command line tool. I have been able to complete the game but I am not able to find out how to restart the game so that the user can play again after winning or losing. Any advice?
Given that no details or code were given, i'll say you may use a loop. You probably are storing the game state in variables. When the game reaches the end, the loop should restart, restoring all game data to the initial state. If you have any doubts, read this section of the Swift documentation about control flow (it has examples with games, yay):
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
Felipe Borges got started but I wanted to provide a concrete example on how one might design such a game:
var playAgain = true
repeat {
print("The game starts!")
// The user plays
// Response is a game-state variable
let response = readLine()
print("The game is over yay!")
print("ask the user whether to play again?")
playAgain = false // whatever the user does goes here
} while playAgain
The two most important things to keep in mind are the loop and the game state. The game state should be scoped inside a function or loop so that the next iteration of the game starts over with new values. In my example, there are no variables pertaining to specific game states outside of the repeat {} while loop, so each iteration starts fresh (the response variable being the example here).

Transparent layer Unity

In my scene I have 2 camera(split screen). it's possible change the trasparency of a layer only for one camera? for examples the "layer1" have alphatrasparency = 0.5 for right camera while left camera show "layer1" without trasparency.
Ostensibly no
There's a way to do it, though. It's a bit of a hack though, as it doesn't depend on physics layers, but rather the presence of a custom monobehavior script. Here's what I remember about this off the top of my head (I can dig up an implementation later, if needed).
Step 1: you will need a MonoBehaviour script attached to every game object you want to have rendered differently. This script is absolutely essential.
Step 2: this script will contain one function (you can use an existing behaviour script if all the objects already have one in common and you can just add this function to that script). Call it whatever you want, but something like AboutToBeRendered(Camera cam)
Step 3: create another script and attach it to both cameras. This script will also have one function in it: OnPreRender()
Step 4: In this OnPreRender method you will need to do:
find all game objects from Step 1
get their component with the AboutToBeRendered method
invoke that method, passing the camera as the paramter
Step 5: Writing the AboutToBeRendered method.
determinie which of the two cameras was passed to the method
set the material's color to be transparent or not, as needed
OnPreRender() is only called on scripts with a camera component on the same GameObject, indicating that this camera is about to render the scene. But what we actually want is for the object about to be rendered to know that it's about to be rendered and by which camera. Which is why we need the script in step 1.
I suppose you could skip step 1 and only look at every object in the scene and look at its physics layer, but that's going to be more expensive to figure out than "get me all instances of this component." You could do it based on Tag instead, as FindObjectsWithTag is generally considered to be pretty fast, but if you're already using the tag for something else, you're out of luck, and there's no comparable method for getting objects in a given physics layer.
However, you'd have to tweak the material's alpha value in the camera script rather than letting the object itself decide what value it should be.
In either case, the object's material would need to support transparency. When I did this I was preventing the object from being rendered entirely, so I just disabled its MeshRenderer component.

Unity2d - Destroying Object using Destroy(gameObject) // it will destroy the object with which the script is attached to

I am Creating Unit2D game & i am new to it , where i have written code for Destroying Player Bullete when it hits to Meteorite(or enemy).
I have one Bullete PREFAB. to which Destroybullete script is attached. where i have written normal code under TRIGGER function (C# script).
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "meteorite") // have given meteorite tag to meteorite PREFAB
{
Destroy(gameObject)
}
}
I want to know is it correct way to destroy any object. because it keeps showing me msg that "Avoid destroying object to avoid data loss".
AND THE MAIN THING.
This code works well in Unity Editor ( Build Settings set to android).
But if i build and create APK of it .......... on my android mobile(redmi 1s) , it is not working.Bullete starts firing automatically ( as required) but as any bullete hits meteorite than game lags for miliseconds and bulletes stops firing....AND THE SAME CODE WORKS FINE UNDER UNITY.
DOES TO MEAN I HAVE KILLED bullete prefab for ever by writing Destroy(gameObject).
need Explanation and solution for correct way destroying objects.
The correct way to destroying objects is not destroying them :).
The msg you are getting in console inside Unity is just a warning to try avoiding destroying objects, main reason is being that Destroy and Instantiate are VERY expensive commands and they are often used a lot (like your example, instantiating every bullet then destroying it).
Reason why it works well on PC is because you have much higher processing power of hardware compared to mobile and the lag you are getting on mobile is the time it takes to finish Destroy command (or Instantiate).
The way you can avoid using Instantiating and Destroying objects is by using object pooling, it is a simple way to reuse small pool of objects.
Here is a simple way how you would implement it:
1. Instantiate let's say 5 bullets at start and hide them inside barrell or something like that.
2. Fire the first bullet from barrel and when it hits something just move it back to barrel at the end of array.
3. Keep reusing the bullets
You have good in-depth explanation about object pooling here : https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
But you can get away with much less understanding of object pooling, if this is too long try searching online something like "Unity3D object pooling" and find simpler tuorial.

Difference btw. sendmessage and setting Value

What is the difference between those two methods? Why should i prefer one?
1)
GameObject.FindGameObjectWithTag("").GetComponent<Rocket>().active = true;
2)
GameObject.FindGameObjectWithTag("").GetComponent<Rocket>().SendMessage("setActive");
thanks!
Sending a message searches through all the components of the gameObject and invokes any function that has the same name as the message. Not a 100% sure but Im sure this uses reflection which is generally considered slow.
SetActive() or the active variable set the gameObject as active or not. If its not active it wont render in the scene and vice versa.
First of all it seems there are several inconsistencies with your code above:
1) Components (and MonoBehavior) don't have an active property (active belongs to GameObject), so the first line of code shouldn't compile. In addition the most recente version of unity don't have active anymore, it's substitued with activeSelf and activeInHierarchy.
And btw, both activeSelf and activeInHierarchy are read only, so you can't assing directly a value to them. For changing their value use SetActive method.
2)
The second line of code shouldn't work either (unless Unity does some magic behind the scenes) because SetActive methods belong to GameObject and not to your Rocket Component.
Now, I suppose your question was the difference between:
gameObject.SetActive(true);
and
gameObject.SendMessage("SetActive",true);
The result is the same, but in the second way Unity3D will use reflection to find the proper method to be called, if any. Reflection has an heavy impact on performance, so I suggest you to avoid it as much as possible.