Helpful Code Snippets

Ok, so there are several little things that I have made or someone else has made that I think could really help everyone out, so here is a thread to post all those little helpful things. It works like this, you say what your posting, what it does, the code, and then anything else that might be required.

I’ll start it off.

Ok so here is a script that turns off other scripts when your character leaves the collider.
Here is the code

var shouldBeEnabledOnStart = false;
function Start () {
 	var scripts = gameObject.GetComponentsInChildren (YOUR_SCRIPT_HERE, true);
	if (!shouldBeEnabledOnStart) {	
			for (var tmp : YOUR_SCRIPT_HERE in scripts) {
			    tmp.enabled = false;
			}
	}
	
	else {
		for (var tmp : YOUR_SCRIPT_HERE in scripts) {
		    tmp.enabled = true;
		}	
	
	}

}


function OnTriggerEnter (colid : Collider) {
	
	if (colid.gameObject.tag == "Player") {
		var scripts = gameObject.GetComponentsInChildren (YOUR_SCRIPT_HERE, true);
		for (var tmp : YOUR_SCRIPT_HERE in scripts) {
		    tmp.enabled = true;
		}
	}
}

function OnTriggerExit (colid : Collider) {
	if (colid.gameObject.tag == "Player") {
	var scripts = gameObject.GetComponentsInChildren (YOUR_SCRIPT_HERE, true);
		for (var tmp : YOUR_SCRIPT_HERE in scripts) {
		    tmp.enabled = false;
		}
	}
}

What you do to set it up is make a empty object, then add a box collider, set Is Trigger to true, then attach this script to it. Add child objects with the script you want to turn off to the game object with the box collider. Edit YOUR_SCRIPT_HERE with what ever script that is in the child objects that you want to turn off. Note: for this to work you have to tag your main character with tag, “Player” (or of course you could change the “if (colid.gameObject.tag == “Player”)” to something else).

It works pretty good, tested it with about 5000 revolving coins that move up and down, got it so when using this box there wasn’t a noticeable decrease of frame-rate. When I tried again without this box it went down to about .5-2FPS.

Heres some code to do something when you shake your device…

var kEraseAccelerationThreshold = 2.0;

function Update () {

var accel = iPhoneInput.acceleration;

   var x = accel.x; 
   var y = accel.y; 
   var z = accel.z; 
    
  var length = Mathf.Sqrt(x * x + y * y + z * z);
    
      if (length >= kEraseAccelerationThreshold) {

      	// DO STUFF HERE

		} 
}

And heres some code to use the “pinch” feature

  if ( iPhoneInput.touchCount == 2 ) 
   { 
      var touch1 : iPhoneTouch = iPhoneInput.GetTouch( 0 ); 
      var touch2 : iPhoneTouch = iPhoneInput.GetTouch( 1 ); 
       
      if ( touch1.position.x < touch2.position.x ) 
         Camera.main.transform.position.z -= ( touch1.positionDelta.x - touch2.positionDelta.x ) / 10; 
      if ( touch1.position.x > touch2.position.x ) 
         Camera.main.transform.position.z += ( touch1.positionDelta.x - touch2.positionDelta.x ) / 10; 
       
      if ( touch1.position.y < touch2.position.y ) 
         Camera.main.transform.position.z -= ( touch1.positionDelta.y - touch2.positionDelta.y ) / 10; 
      if ( touch1.position.y > touch2.position.y ) 
         Camera.main.transform.position.z += ( touch1.positionDelta.y - touch2.positionDelta.y ) / 10; 

       
      if ( Camera.main.transform.position.z > -2 ) 
         Camera.main.transform.position.z = -2; 
      if ( Camera.main.transform.position.z < -15 ) 
         Camera.main.transform.position.z = -15; 

   }

NOTE: You can change the object you are moving to something else other than the camera, that was just for the example.

from here: http://forum.unity3d.com/viewtopic.php?t=16610&highlight=pinch

function TouchForGUI(object : GUIElement, touch : iPhoneTouch) : boolean { 
   var rect = object.GetScreenRect(camera); 
   if (rect.Contains(touch.position)) 
   return true; 
    
   return false; 
}

You would use it in a Update() or a FixedUpdate() and do a ‘if’ statement checking to see if mouse(0) is down (AKA: a finger is touching the device) then you would use the TouchForGUI function. I don’t know much about the performance for this though.

Just found out that that code needs to be slightly adjusted, the quote should have it right.

great stuff.
keep up the good work.
it’s a shame that the unity staff can’t find the time to make tutorials for unity iphone…

Here is something that isn’t quite a code snippet, but one of the best “web apps” that I have seen that helps iPhone devs.

http://www.moopf.com/appstorereviews/

Enter your application ID, or the application link and it will gather comments/ratings from all countries. Extremely helpful!

I didn’t write this, but once again it is incredibly useful. If you have 3D text and don’t want to be able to see it through walls, use this shader instead of the default text shader.

Shader "GUI/Text Shader DRO" {
	Properties { 
	   _MainTex ("Font Texture", 2D) = "white" {} 
	   _Color ("Text Color", Color) = (1,1,1,1) 
	} 

	SubShader { 
	   Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } 
	   Lighting Off Cull Off ZTest Always ZWrite Off Fog { Mode Off } 
	   Blend SrcAlpha OneMinusSrcAlpha 
	   Pass { 
	      ZTest LEqual 
	      Color [_Color] 
	      SetTexture [_MainTex] { 
	         combine primary, texture * primary 
	      } 
	   } 
	} 
	}

Just kinda something for all the noobs (like my self), to change cameras, change the Camera.depth variable to be bigger then the other cameras (default is -1 I believe)

wow these are really helpful… thanks guys :smile:

Let me disagree with you. Please read this topic for details.

and seems like this is one more topic to add to FAQ :stuck_out_tongue:

The tutorials that Unity has right now are great, and I look forward to when they have more.

Here’s an improved pinch/zoom snippet:

iPhoneTouch touch = iPhoneInput.GetTouch(0);
iPhoneTouch touch2 = iPhoneInput.GetTouch(1);

// Find out how the touches have moved relative to eachother:
Vector2 curDist = touch.position - touch2.position;
Vector2 prevDist = (touch.position - touch.positionDelta) - (touch2.position - touch2.positionDelta);

float delta = curDist.magnitude - prevDist.magnitude;

Then use “delta” to change your camera position/ortho size, etc, depending on your setup. “delta” is basically how much the user zoomed in or out.

Just to make sure, that is C# code, correct?

Yep.

Great! Very useful! :smile:

I just want to say thanks to everyone who posted snippets in this thread. Please keep them coming.

!!!

-JC

Thanks for this! Really helpful.

I can’t wait to see the iPhone tutorial that Demo Team is making. But I find it, sometimes, more helpful to see these code snippets. I come from an art background and have more difficulty writing code than anything else. And to see these small snippets helps me to understand what is being done and how to go about writing my own code.

I agree! I’m also more of an artist, and getting to see and use working code is a big help! Thanks alot!

Ok here’s something I have been working on for a project I have been working on.
Attach this to your character or some object (the main thing is only attach it once).

This will successfully call OnMouseDown and OnMouseUp to GUI objects and actual objects. Once adding this in, in the object that you want to dettect touches on you do something like this.

function OnMouseDown () { // or function OnMouseDown(position : Vector2)
print(“HELLO WORLD”);
}

var touchForGUI = false;
var touchForObject = false;
var tmpobj : Transform;
var touch : iPhoneTouch;
var distance = 10.0;

function Update () {
	
	
	if (iPhoneInput.touchCount > 0) {

	   touch = iPhoneInput.GetTouch(0);
		
		// ======================================================
		// ================== SECTION: GUI OnMouseDown
		// ======================================================
		if (!touchForObject) {
		var guiz : GUIElement[] = GameObject.FindObjectsOfType(GUIElement);
		var GUIi;
		for (GUIi in guiz) {
			if (TouchForGUI(GUIi, touch)) {
				touchForGUI = true;
				GUIi.SendMessage("OnMouseDown", touch.position, SendMessageOptions.DontRequireReceiver);
				tmpobj = GUIi.transform;
			}
		}
	}
		// ======================================================
		// ================== SECTION: transform OnMouseDown
		// ======================================================
		if (!touchForGUI) {
		var ray = Camera.main.ScreenPointToRay (Vector3(touch.position.x,touch.position.y ,0));
		var hit : RaycastHit;
		if (Physics.Raycast(ray.origin, ray.direction * distance, hit)) {
			touchForObject = true;
			tmpobj = hit.transform;
			hit.transform.SendMessage("OnMouseDown", touch.position, SendMessageOptions.DontRequireReceiver);
		}
		// ======================================================
		// ================== SECTION: transform OnMouseUp
		// ======================================================
		
	}
		
	
}

else {
	if (touchForGUI) {
		touchForGUI = false;
		touchForObj = false;
		tmpobj.SendMessage("OnMouseUp", touch.position, SendMessageOptions.DontRequireReceiver);
	}
	
	else if (touchForObject) {
		touchForObject = false;
		touchForGUI = false;
		tmpobj.SendMessage("OnMouseUp", touch.position, SendMessageOptions.DontRequireReceiver);
	}
	
}

}



function TouchForGUI(object : GUIElement, touch : iPhoneTouch) : boolean {
	var rect = object.GetScreenRect(Camera.main);
	if (rect.Contains(touch.position))
	return true;
	
	return false;
}