• Advertisement
Sign in to follow this  

Unity Basic Srcipting help in unity

This topic is 1394 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all,  I'm just beginning to learn unity scripting. I'm trying to implement them as I learn some very basic functions along the way.

 

This link from unity taught me the basics of OnCollisionEnter() - which, as far as I understand, executes some piece of code whenever it detects collisions with a gameobject (there they named it as prop_powerCube). 

 

Now I tried to implement it in C# and I had something like:

using UnityEngine;
using System.Collections;

public class Mine : MonoBehaviour {

	// Use this for initialization
	void Start () { 
		int health=10;
	
	}
	
	// Update is called once per frame
	void Update () {
		

//public class DestroyCubes : MonoBehaviour
{
     OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "Sphere")
        {
            //Destroy(col.gameObject); 
            health-=5;
        }
    }
}
   Debug.Log("Health=", health);
    }
	
	


In short, it would detect collisions with 'Sphere' and decrease the health of the player by 5. The problem I understand is with "col". 

 

It is a variable of type Collison. But how do I explicitly declare it in this case? 

 

MY AIM: WHENEVER MY PLAYER COLLIDES WITH A SPHERE, HIS HEALTH DECREASES BY 5 UNITS.

 

Please guide me where am I missing it...

Share this post


Link to post
Share on other sites
Advertisement
OK.  The first thing you must learn is the difference between a "member variable" and a "local variable".
 
Your "health" variable is currently local to your Start method.  That means that no other method can actually access it.
 
In order for your health variable to be used by all of the methods of your class, you need to declare it as a member variable:
 
public class Mine : MonoBehaviour
{
    int health;  // this is a member variable

    void Start()
    {
        health = 10; // this sets the member variable.  notice the "int" part is removed because I don't want to declare a different variable here.
    }
The second thing is that for MonoBehaviours that you attach to scene objects or prefabs, Unity only wants you to put one behavior in a single file (this is because Unity internally identifies component types using a unique ID, not the class names). So if you want that DestroyCubes class, you'll have to put it in a DestroyCubes.cs file.

The third problem is that you cannot perform Debug.Log outside of a function like you're doing in your post. Edited by Nypyren

Share this post


Link to post
Share on other sites

Thanks for the help. I'm having some real trouble with scripts. I don't know why, but what I did as an experiment was put a cube and then whenever I collide with the cube, I'd like to display a message..

 

I wrote this code, applied it to my player character, and yet on collision with the cube nothing happens :(

function OnCollisionEnter(theCollision : Collision){
 if(theCollision.gameObject.name == "Cube"){
  Debug.Log("I hit it");
 }else {
  Debug.Log("Hit the wall");
 }
}

Share this post


Link to post
Share on other sites
Things to check:

- Make sure at least one object has a Rigidbody/Rigidbody2D.
- Make sure you aren't mixing 2D and 3D components.
- If you are using 2D components instead of 3D components, change to "OnCollisionEnter2D" and "Collision2D" in your function (this caught me off guard for a while myself).

Share this post


Link to post
Share on other sites

Somehow the Debug.Log function has stopped working, it seems.

 

I deleted my entire scene, created a very elementary plane and placed a cube (A 3D RIGID BODY) on top of it.

 

Then I applied the following script on the cube:

using UnityEngine;
using System.Collections;

public class debug : MonoBehaviour {

	void Example() {
        Debug.Log("Hello", gameObject);
       
    }
} 

I hoped to see a 'Hello Cube' on my console screen. Well nothing really happened.

I have checked  clicking the three buttons on the top right of the console screen - up to no avail.

 

On another note: Is there a 'beginner' way to print things right on the game window? Like, if you collide with an object a pop-up will display something like: "Game over" etc. 

Perhaps then, I can do away with this debug.log not working, this has left me quite frustrated after trying to sort it out for almost a couple of hours by now.. 

Edited by Bubu Bhat

Share this post


Link to post
Share on other sites
In your most recent post, the reason why your Debug.Log isn't working is probably because nothing actually calls your Example function.

Unity automatically calls certain functions, but they have to be named specific things:

- Awake is called when your component is being created.
- Start is called for active components after all other components have had their Awake function called.
- Update is called once per frame per active component.
- OnDestroy is called when a component is being destroyed.

Other ones are listed here, in the "messages" section: http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.html

In addition to those functions, you can make your own functions, but Unity won't call them automatically - you will have to call them yourself (which eventually has to be traced back to one of the methods that Unity calls).



For your second question, Unity's built-in way to draw text and stuff to the screen is to use the "OnGUI" method (that's one of the ones listed in the link above).

The basic process of using OnGUI is:

- Make a method called 'void OnGUI()' in your class.
- Inside that method, call functions such as http://docs.unity3d.com/Documentation/ScriptReference/GUI.Label.html to display labels, buttons, etc.

Most of the useful methods are in these two classes:

http://docs.unity3d.com/Documentation/ScriptReference/GUI.html
http://docs.unity3d.com/Documentation/ScriptReference/GUILayout.html


For more advanced games, I recommend not using Unity's current GUI system - it is not flexible enough. This may be changed in future versions of Unity, but for now, I prefer the third-party "NGUI" library instead. But for simple things, Unity's built-in GUI system works fine and requires writing very little code. Edited by Nypyren

Share this post


Link to post
Share on other sites

Thanks for all of this.

 

Just a request: can you kindly give me the full code of the C# file to simply output a message via Debug.Log once my player character collides with a cube in 3D? One such instance of the full code will be of great help. Thanks..

Share this post


Link to post
Share on other sites
using UnityEngine;

public class Example : MonoBehaviour
{
    void OnCollisionEnter(Collision collision)
    {
        Debug.Log("3D Collision with another object named: "+collision.gameObject.name);
    }
}
Then make sure you attach that component to your player object, and make sure that object also has a collider and rigidbody, and you should be set.

If you still don't see a log message, you might have accidentally disabled log messages in the console window. There are some toggle buttons in the upper right corner of the console log window which enable and disable Debug.Log, Debug.LogWarning and Debug.LogError, respectively. Edited by Nypyren

Share this post


Link to post
Share on other sites

Thanks a ton. It's working almost the way I want it to. Added a rigidbody component to the cube and suddenly it began to fall through the terrain, so searched in google and applied a mesh collider  with the 'convex' option ticked, and the cube stayed on the terrain.

 

Just a small tweak, the game starts with printing the statement: "3D Collision with another object named: Terrain" even tough the y-coordinate of both the player and the terrain are the same. PRoblem is when I collide with the cube, it says nothing.... So I changed the code to

void OnCollisionEnter(Collision collision)
	
		{ if (collision.gameObject.name=="Cube")
		{
        Debug.Log("3D Collision with another object named: "+collision.gameObject.name);
		}
		}
	

Even this does not output anything upon collision with the cube..

I also tried experimenting with the Collision Detection options - but to no avail sad.png

 

Somehow the cube is not detecting collision, even though I can't directly pass through the cube.

Edited by Bubu Bhat

Share this post


Link to post
Share on other sites

Attached is a screenshot of my Unity Window with the Cube selected..

 

[attachment=20560:Untitled.jpg]

Share this post


Link to post
Share on other sites
OK, I see what's up. Your cube has the "Is Trigger" flag enabled.

http://docs.unity3d.com/Documentation/ScriptReference/Collider-isTrigger.html

IsTrigger changes the behavior of the collider in the following ways:

- It participates in collision detection, but doesn't participate in rigid-body physics. In other words, stuff can pass right through it.
- When another collider enters it, Unity calls OnTriggerEnter instead of OnCollisionEnter.
- When another collider exits it, you get OnTriggerExit instead of OnCollisionExit.
- You can use this to script things that happen when you move inside the trigger zone, like a proximity-sensitive door or a laser tripwire.

If you want it to act as a physical cube that you can collide with, just disable the IsTrigger flag. If you want to use it as a trigger zone, add OnTriggerEnter and OnTriggerExit methods. Edited by Nypyren

Share this post


Link to post
Share on other sites

Also i believe the enter is only called once, so if it enters but never leaves you won't get multiple calls. If you need to do something while the objects are colliding use OnTriggerStay or OnCollisionStay.

 

It sounds like your objects might be in contact the first frame and so its printing to the log. But since they don't move away no more enter events are generated.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By Chamferbox
      Chamferbox, a mini game asset store has just opened with some nice game assets, 
      Here you can find a free greek statue asset 

      Also check their dragon, zombie dragon and scorpion monster out:



      They're running the Grand Opening Sale, it's 30% off for all items, but for gamedev member, you can use this coupon code:
      GRANDOPEN
      to get 50% off prices What are you waiting for, go to
      http://chamferbox.com
      and get those models now!

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By DevdogUnity

      Ho ho ho
      Tis the season of Christmas surprises, and we have a awesome one for you! 🎅  
      Sponsored by all your favorite Unity Asset Store developers, Nordic Game Jam, Pocket Gamer Connects, and co-hosted by Game Analytics, we (Joris and I – Devdog) are launching the second edition of our yearly Christmas Giveaway Calendar for all Unity game developers!
      You can already now sign up right here.
       
      So what’s this all about?
      For the past weeks, we’ve been collecting sponsored gifts related to Unity (asset vouchers, product keys, conference tickets etc.), and throughout each day of December leading up to Christmas Day on the 25th, we will be sending out these sponsored gifts as early gamedev Christmas presents via e-mail to hundreds of lucky winners.
      The total prize pool is at $35,000, with over 1200 presents donated by the awesome sponsors!
       
      Merry Christmas from Devdog, Game Analytics, and every single one of the sponsors.

      View full story
    • By sveta_itseez3D
      itSeez3D, a leading developer of mobile 3d scanning software, announced today a new SDK for its automatic 3D avatar generation technology, Avatar SDK for Unity. The Avatar SDK for Unity is a robust plug-n-play toolset which enables developers and creatives to integrate realistic user-generated 3D avatars into their Unity-based applications. SDK users can allow players to create their own avatars in the application or integrate the SDK into their own production processes for character design and animation.
      “Virtual avatars have recently become increasingly popular, especially in sports games and social VR apps. With the advance of VR and AR, the demand to get humans into the digital world is only increasing”, said Victor Erukhimov, itSeez3D CEO. “Our new Avatar SDK for Unity makes it super-easy to bring the avatar technology into any Unity-based game or VR/AR experience. With the Avatar SDK for Unity now every developer can bring face scanning technology into their games and allow players to create their own personalized in-game avatars, making the gameplay much more exciting and immersive.”
      Key features of the Avatar SDK for Unity:
      Automatic generation of a color 3D face model from a single selfie photo in 5-10 seconds (!). Works best with selfies, but can be used with any portrait photo.
      Shape and texture of the head model are unique for each person, synthesized with a deep learning algorithm crafted by computer vision experts
      Head models support runtime blendshape facial animations (45 different expressions)
      Generated 3D heads include eyes, mouth, and teeth
      Algorithms synthesize 3D meshes in mid-poly resolution, ~12k vertices, and ~24k triangles
      Six predefined hairstyles with hair-recoloring feature (many more available on request)
      Avatar generation API can be used in design-time and in run-time, which means you can allow users to create their own avatars in your game
      Cloud version is cross-platform, and offline version currently works on PCs with 64-bit Windows (support for more platforms is coming soon)
      Well-documented samples showcasing the functionality.
       
      Availability
      The Avatar SDK for Unity is offered in two modes - “Cloud” and “Offline”. The “Cloud” version is available at http://avatarsdk.com/ and the “Offline” version is available by request at support@itseez3d.com.
      ###
      About itSeez3D
      At itSeez3D, we are working on the computer vision technology that turns mobile devices into powerful 3D scanners. itSeez3D has developed the world's first mobile 3D scanning application that allows to create high-resolution photorealistic 3D models of people's' faces, bodies and objects. The application is available for iOS and Windows OS mobile devices powered with 3D cameras. In 2016 the company introduced Avatar SDK that creates a realistic 3D model of a face from a single selfie photo. To learn more about itSeez3D scanning software and 3D avatar creation technology, please visit www.itseez3d.com and www.avatarsdk.com.

      View full story
    • By khawk
      Unity has posted the Unity Austin 2017 playlist on YouTube. From their tweet:
      View the full playlist at https://www.youtube.com/playlist?list=PLX2vGYjWbI0TI_C4qouDw7MSSTFhKJ6uS or below:
      .

      View full story
  • Advertisement