Monday, March 31, 2014

unity3d - hit all objects on the screen or hit only one object on the screen click

Here is an example code:


//hit only 1 object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitScreenObject;
if(Physics.Raycast(ray,out hitScreenObject))
{
if(Input.GetMouseButtonDown(0))
{
//isHit = false;
Destroy(hitScreenObject.collider.gameObject);
}
}

//hit all objects at the same time
RaycastHit2D[] hits;
//hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
//Ray2D ray = Camera.main.ScreenPointToRay(Input.mousePosition, Vector2.zero);
                //Physics2D.raycastsHitTriggers = true;
               
                hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
               
           


Wednesday, March 26, 2014

Unity3d Preloading Scenes with allowSceneActivation = false working (Loading scene in background)

Loading Scene in Background without switching the level immediately.


Read below to find a working (and tested)  way of loading scene in background in Unity3d. Also it wont  switch next level immediately.

If you are trying to preload a new scene, you have to use Application.LoadLevelAsync("sceneName"); method. I have managed to use this function with allowSceneActivation=false. When you set allowSceneActivation to false, you will probably sett that Unity Editor hangs. This is why you must use a different approach to achieve preloading.

IF allowSceneActivation locks up  Unity Editor  try this script:

IEnumerator LevelLoaderProcess() {
AsyncOperation status = Application.LoadLevelAsync("gameScreen");
status.allowSceneActivation = false;

// Wait until done and collect progress as we go.

//while( !status.isDone )
//{
loadProgress = status.progress;
if( loadProgress >= 0.9f )
{
Debug.Log("almost done");
// Almost done.
//break;
}
yield return null;
//}

while (!doLoadNextFrame) {
Debug.Log("still waiting");
                       //You can do whatever you want here...  
yield return new WaitForSeconds(1.0f);
}
// Allow new scene to start.
status.allowSceneActivation = true;
//yield return status;
}

You see that 0.9f if condition? Well that is the trick. When you set status.allowSceneActivation to false, unity3d stops loading target scene as soon as it loads  %90 of scenes content. And starts to wait for that 10 percent to load the next scene.  To load that 10% data, Unity3d will be waiting for status.allowSceneActivation = true; command.

Script I share above handles this issue.


Another thing to notice. DO NOT put your StartCoroutine command in AWAKE function. This also makes  unity crash, your editor crashes which makes it unresponsive. This is a Untiy3d bug I believe.  You can put a gui button in your  OnGUI  method to start your coroutines. Like this:

void OnGUI()  {
if (GUI.Button (new Rect (10, 10, 50, 50), "sirinlike")) {
StartCoroutine (LevelLoaderProcess());
}
}





Tuesday, March 25, 2014

fonts for your unity3d games

Font sites:
1) da font: http://www.dafont.com/
Both free and paid fonts. A few cool ones:

+ Laurus Nobilis  : Roman senate games.


----

and if you are wondering how to display your fonts, text, etc.. be sure to read : http://johnstejskal.com/blog/unity3d-how-to-make-a-2d-gui-hud-interface-to-display-scorelives


---

changing the sprites:
http://forum.unity3d.com/threads/212619-Mini-tutorial-on-changing-sprite-on-runtime

unity3d - mechanim animator tutorial videos

1) a quick usage: http://www.youtube.com/watch?v=HXN9lq9syTE

Monday, March 24, 2014

instantiate object at mouse position - change mouse position to world position.

If you are trying to instantiate a gameobject when player clicks on surface, you have to find the world point of the tabbed place. Then you can instantiate your object. 

You can get hit.point to find where the object is hit. If you are trying to make a shooting game. This will give you the world position. 

Or you can use mouse position and since mosue position is screen coordinates you change it into world position. 

Input.mousePosition is in screen coordinates (in pixels)

To get a position in world coordinates you need to use Camera.main.ScreenToWorldPoint(Input.mousePosition). 

Input.mousePosition is also a 2 dimensional position (because your screen is flat). To get a correct and meaningful world position you will also have to specify a z coordinate to describe how far in front of the camera the world point should be. So if you have a camera looking straight down onto a plane and the camera has a distance of 10 to the plane you would set the z coordinate to 10 to instantiate something on that plane.

here is an example code which gives the world point of Input.mousePosition. 

Vector3 myPos = Input.mousePosition;

myPos = Camera.main.ScreenToWorldPoint(myPos);

myPos.z = 10f;   //you have to modify z coordinate since it will always give you the camera's z position. 


here is an other code which I find on http://answers.unity3d.com/questions/32807/instantiate-object-at-mouse-position.html page. 


  1. Vector3 mousePos=new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);
  2.  
  3. if(Input.GetMouseButtonDown(0)) {
  4. Vector3 wordPos;
  5. Ray ray=Camera.main.ScreenPointToRay(mousePos);
  6. RaycastHit hit;
  7. if(Physics.Raycast(ray,out hit,1000f)) {
  8. wordPos=hit.point;
  9. } else {
  10. wordPos=Camera.main.ScreenToWorldPoint(mousePos);
  11. }
  12. Instantiate(thePrefab,wordPos,Quaternion.identity);
  13. //or for tandom rotarion use Quaternion.LookRotation(Random.insideUnitSphere)
  14. }


hope this helps.

useful links:

+ http://forum.unity3d.com/threads/50321-2D-screen-coordinates-to-3d-world-coordinates


Saturday, March 15, 2014

Rigidbody - collider - isKinematic - isTrigger in nutshell

Rigidbody : allows a gameobject to be effected by forces like gravity or movement. collider: it is a must to detect collisions. If you are after object collisions then both two objects must have their own collider and at least one of them must have a rigidbody.

isKinematic : if this is selected then the gameobject will NOT be effected from forces!

isTrigger : when this is selected, there will be no collisions but gameobject will be effected by forces!

Thursday, March 13, 2014

free musics for your unity games

Here another list of pages that you can use free for your mobile games. List will be added up in time. So be sure to check this page in the future. 1) http://www.songsfromthelostland.com/#more 2) http://soundcloud.com, be sure to check search>sound>>license to listen to>>modify commercially. there you will find tons of royaly free music. 3) http://www.soundsnap.com/ 4) http://www.audionetwork.com/sound-effects 5) http://www.musicloops.com/ 6) www.incompetech.com 7) www.danosongs.com 8) www.jewelbeat.com and a free music loop that you can direclty download free from unity3d asset store: https://www.assetstore.unity3d.com/#/content/14478 and if you want to compose your own music, here are a few tools: + NI Maschine (expensive) + Reaper (DAW) + google about VST (for some Sythies ect) then buy yourself a little MIDI-Keyboard and check out YouTube for tutorials. + http://www.vst4free.com/ + http://www.reaper.fm/

best unity 2d tutorials

Hee I will gather 2d game making tutorials that I fidn interesting. List will add up in time. Be sure to check this page later. 1) a real nice tutorial for 2d games on unity3d. http://pixelnest.io/tutorials/2d-game-unity/ 2) http://makeitatyourlibrary.org/technology/make-2d-video-game-unity#.Ux1ZGfmSxHX http://makeitatyourlibrary.org/technology/make-2d-video-game-unity#.Ux1ZGfmSxHX

Thursday, March 6, 2014

isometric games - find a great tutorial

This guy here :
http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511

has a great tutorial on isometric gaming.

be sure to check it out :)

Unity3D Raycast with LayerMask - How layermask works? Working example of Raycasthit and RaycastHit2D and LayerMasks , both in 2D and 3D.

You can select which layers to cast raycast in Unity3D. You can exclude some layers or you can select only the ones you want.

Unity3D uses LayerMask as an 32 bit integer. This is why you also have only 32 avaible layer slots. Each of this layers are marked as bits of that 32 bit integer. So you need to do some bit

With these operators below, you can do all your LayerMask operations.
1) bit shift operator (<<)
2) bit inverse operator (~)
3) bitwise (binary) OR operator (|)

dont worry it is much easier then it sounds :)


Here is how LayerMask represented really:
0000 0000 0000 0000 0000 0000 0000 0000
first on the right one is the first Layer you see on your unity editor.
second one comes from the second on the right.,
 so goes on like this.

You have to create LayerMask in unity like this:
int  ExitButtonLayerMask = 1 << ExitButtonLayer;
ExitButtonLayer is an integer. You get the layer numbers from unity editor.
then use the Mask on your raycast, there you get your ray which only hits only the objects which reside on your chosen layers.


Here is an example class:



public class Raycast2D : MonoBehaviour {

int ExitButtonLayer;

int RateButtonLayer;

int ExitButtonLayerMask;

int RateButtonLayerMask;

int CombinedMask;

void Awake() {

//open your unity editor, and look at layers, click "Add layer" button if you need to see the layer numbers.

ExitButtonLayer = 8;

RateButtonLayer = 9;

//ok, lets add our layers. these layers will be affected when a ray hits them:

ExitButtonLayerMask = 1 << ExitButtonLayer;

RateButtonLayerMask = 1 << RateButtonLayer;



// This is the binary OR operator, this is how we combine different masks.

CombinedMask = ExitButtonLayerMask | RateButtonLayerMask;

//btw if you want to "omit" these layers above, then you must combine them first then exclude them

// like this: ~((1 << ExitButtonLayerMask) | (1 << ExitButtonLayerMask))

}



void Update() {

if (Input.GetMouseButtonDown (0)) {

//RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

//here we use our combined layer mask, so taht unity will cast a ray on the objects which are on these layer masks. Other objects wont get affected.

RaycastHit2D hit = Physics2D.GetRayIntersection (ray, Mathf.Infinity, CombinedMask);

if (hit.collider != null) { 

Debug.Log ("object hit: " + hit.collider.gameObject.name + " , Target Position: " + hit.collider.gameObject.transform.position); 

} /*else {

Debug.Log("missed");

}*/

}

}



}



examine the code above and ask me questions if you need.
also be sure to read http://forum.unity3d.com/threads/211708-Unity-2D-Raycast-from-mouse-to-screen , MelvMay MelvMay (Unity Developer) explained 2d ray hit in 3d space.


Related Unity3d Documentation Links:
1)  Physics2D.GetRayIntersection  : Cast a 3D ray against the colliders in the scene returning the first collider along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersection.html)
2) Physics2D.GetRayIntersectionAll  : Cast a 3D ray against the colliders in the scene returning all the colliders along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersectionAll.html)
3) Physics2D.GetRayIntersectionNonAlloc  : Cast a 3D ray against the colliders in the scene returning the colliders along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersectionNonAlloc.html)
4) Found a good reading on unity3d layermask issue with raycast ignore. try http://answers.unity3d.com/questions/8715/how-do-i-use-layermasks.html good article on different approaches, including bit values and operators.



Saturday, March 1, 2014

Unity3d Enum - How to loop Enum with foreach in Unity

If you want to iterate through your enum class members in Unity3d with C#,  you can  use a foreach loop.

Infact Enum class does not implement the IEnumerable interface. This means that you cannot directly loop through all of the declared values using the foreach statement.

But Enum provides a static method named as GetValues.

This gives you an array of your enum class fields.

Like say we have a enum of  unity3d  game object names, like this one:


enum UnityGameObjectNames {
myplayer = 1,
myEnemyZombie,
myFriend
}

and you want to use unity3d gameobject names in one of your functions like start or something. You can do this like this:

void Start() {
foreach (UnityGameObjectNames  unityName in UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + "  is my Unity3d Object Name");
    }
}

or you can also specify array type, so that there wont be extra boxing - unboxing. Unity also runs on mobile devices so any tiny bit of optimization may be needed.

Better set the type of array like this:

foreach (UnityGameObjectNames  unityName in ((UnityGameObjectNames[]) UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + " myObjectName");
    }




as always a few lines of sample code of Unity3d Enum and Foreach:
Sample1:

        //foreach (Madalyalar madalya in (Madalyalar[])Madalyalar.GetValues(typeof(Madalyalar)))
        foreach (Madalyalar madalya in Madalyalar.GetValues(typeof(Madalyalar)))
        {
            Debug.Log(madalya);
            //if (PlayerPrefs.GetInt("m_" + madalya, 0) == 1) {
            //}
        }


Sample 2:
int madalyaDurumu=0;
foreach (MadalyaTipleri madalya in (MadalyaTipleri[])MadalyaTipleri.GetValues(typeof(MadalyaTipleri)))
{
//kazaılmısmadalyalar listesinde var mı ?
if(kazanilmisMadalyalar.Contains(madalya)) {
continue;
}
//eger listede yok ise, playerprefs'e bak, daha önceden kaydedilmis ise listeye ekle.
            madalyaDurumu = PlayerPrefs.GetInt(madalya.ToString());
if(madalyaDurumu == 1) {
kazanilmisMadalyalar.Add(madalya);
}
}

Singleton in Unity3d

Well if you need a singleton, you can use it in Unity3d. 


here is the code:


public class MadalyaMotor : MonoBehaviour {
// Static singleton property
public static MadalyaMotor myInstance { get; private set; }

//public MadalyaMotor()
public void Awake()
{
//-- start of singleton
// First we check if there are any other instances conflicting, better be sure than sorry
if(myInstance != null && myInstance != this)
{
// If that is the case, we destroy other instances
Destroy(gameObject);
}
// Here we save our singleton instance
myInstance = this;
// Furthermore we make sure that we don't destroy between scenes (this is optional)
DontDestroyOnLoad(gameObject);
//-- end of singleton

}
}

Singleton is useful if you want a controller or want o instantiate only one object of a kind. Like audio management , score management, achievement management,.. all  must be done in a static or a singleton object.

Try messing with the code above, put it on an empty unity3d game object, make some functions and call your singleton object from those object. You can make a number of hits singleton controller for example. If you have any questions please do post here.

Well there is also a great blog about this, try http://clearcutgames.net/home/?p=437 if you want further information on singletons. That guy also explains lazy load method of singleton. If you prepfer you can load your gameobjects with lazy load logic so that your singleton object will be created whenever you need them.


Hey i also found a good code example.  Check this out. I also included some helpful page url address so that you can examine them if you want too.

static public bool isActive {
get {
return instance  != null;
}
}

static public MyGameEngine Instance {
get {
//if(instance == null)  {
// instance = Object.FindObjectOfType(typeof(MyGameEngine)) as MyGameEngine;
//}

//some helpful url addresses to check:
//http://answers.unity3d.com/questions/17916/singletons-with-coroutines.html
//http://blog.i-evaluation.com/2013/12/11/creating-game-manager-using-state-machine-and-singleton-pattern-in-unity3d/
//http://forum.unity3d.com/threads/197169-Singleton-vs-Static

if(instance == null)  {
//first time initialize
Debug.Log("instantiate singleton");
GameObject go = new GameObject("_myGameManagerSingleton");
instance = go.AddComponent<MyGameEngine>();
go.transform.position = new Vector3(-20,-20,-20);
//GameObject go  = new GameObject("myGameManagerSingleton", typeof(MyGameEngine));
DontDestroyOnLoad(go);

//Call your other functions to continue inner initialization
instance.DoOtherInitializationStuff();
}
return instance;
}
}

another example (simple yet working great at Unity3d)


private static Singleton instance = null;

 

public static Singleton Instance

{ 

    get { return instance; }   

}

       

private void Awake()

{

    // If instance already exist, destroy ourself.

    if (instance != null && instance != this)

    { 

        Destroy(gameObject);

        return;

    }

 

    // No instance exist yet? We are it.

    instance = this;

 

    // This line exist so that the Singleton would persist between scene loads.

    // Not all singletons needs that.

    DontDestroyOnLoad(gameObject); 

}