Questions in topic: "object-oriented-programming" The latest questions for the topic "object-oriented-programming" Is this method that i use for my coding structrue good? Hi, I'm working on an arcade car game, so i decided to create 3 script: <br> ---- 1. CarController class -> this class contain all car behavior like car handling methods, die method and etc. <br><br> 2. Player class -> player object is a car so it needs CarController script and Player script. Player class contain all player behavior like score variable, Change score method and etc. <br><br> 3. AI class -> AI objects are car so they need CarController script and AI script. AI class contain all AI behaviour like chasing player method and etc. <br><br> So now what's your idea is this method that i use good?! <br> Thanks. object-oriented-programming Sun, 03 May 2020 22:33:46 GMT Eh3an Can't update value of var in another class I have variable 'capacity' which is updating normally, but I can't get an updated value in another class, but initial value is there. Help me :< public class housingPanelScript : MonoBehaviour { public Housing houseObj; public TextMeshProUGUI capacity_txt; public int capacity = 10; void Update() { capacity_txt.text = "max capacity: " + capacity.ToString(); } // some code public void upgradeHouse() { capacity += 10; Debug.Log("capacity " + capacity); } } // Score is updating btw (ontriggerenter2d method) public class Spawn : MonoBehaviour { public GameObject man; int spwCount = 0; public housingPanelScript house; public Destroyer score; public void spawn() { if (score.i < house.capacity && spwCount < house.capacity) { Instantiate(man, new Vector2(-1, 1), Quaternion.identity); spwCount++; } else Debug.Log("not spwn " + house.capacity + " " + score.i); } } object variable value updating object-oriented-programming Thu, 12 Mar 2020 10:49:31 GMT dah41kj How unity works under the hood? ![alt text][1] Hello guys, so i just cant wrap my head around how unity does some things. So first of i have studied a little bit the base classes in unity through visual studio and i came up with this family tree; it shows what classes are derived from what other classes and so on. so my first question is: when a scene is loaded in unity the objects in that scene are instantiated right, so what is the class that the instance of that game object is created from. is it Object or GameObject base class ? My second question is: i understood that the components of a game object are also instances of classes; for example Rigidbody component in the inspector is a instance of the RigidBody class. Now , i have seen that in the base class "Component" there are some properties of type Component, which contain a get; now that property returns a object of type Component, which i feel is useless because anyway in my scrips i cant use that property to access different features of the component due to it not being of the type of the Transform,Rigidbody etc. So why are there those propertys in the Component class having the name of the components but are not of the type of the components?![alt text][2]. Now my biggest confusion come from this: How does the GetComponent(); work, how does it connect and get hold of the actual instance of the Transform component; because if my family tree is correct my script does not inherit from Transform or RigidBody classes. Also there has to be a reason for those Component instances in the Component base class and the individual classes for the components themselves. i Would just like a answer which clarifies everything and explains me how everything works and links together in my family Tree below. Thank You in advance, it means a lot to me if you could explain! ps: @FireStone720 I have seen you have answered some of these questions, do you mind if you give a read my question and say what is on your mind :) Any help from anyone will be very appreciated :) [1]: /storage/temp/119482-family.png [2]: /storage/temp/119483-component.png gameobject component inheritance classes object-oriented-programming Sun, 24 Jun 2018 19:17:12 GMT Luca_Yoy General and OOD advice,General and OOD advice based Hi, I'm relatively new to objected oriented programming and design, and I have a few questions I'm looking for advice on. I'll also take any side-advice you can offer even if it's not related directly to the question but is related to something I said. Thanks! <br><br> 1. I'm trying to work with a tile-based system. I've decided that it would be wise to keep track of all these tiles(for pathfinding and other things), and decided a static List is the way to go about it rather than FindAllObjectsWithTag(). Should a static list containing a reference to every created and destroyed tile exist in the Tile script, or should it exist in a secondary 'TileHelper' script that I've written for other purposes? <br><br> 2. I've created a 'TileHelper' script. The intent was to be used to grab 'shapes' of tiles based off of the origin tile and other inputs. For example, a 3x3 square where the origin is in the center or a 5x5 cross where the origin is in the center. Is this bad design? <br><br> 3. For several of the shapes in this TileHelper script, I use OverlapBox() to get the areas that will be hit. This works pretty well for most shapes (3x3 square), but for others it is not good (a cross that goes diagonal). I've been considering switching to the case where instead I just do math on the vector of the origin tile to get the location of the other tiles. Is there a quick and efficient way to get an object if you know it's exact location, or would it be better to store a Dict where the key is the Vector position and the value is Tile? <br><br> 4. Using these helper functions, I want to be able to make very specific areas that can be targeted by certain spells, and areas that will be impacted by the spell based off of the spell and the targeted tile. I feel like creating a class Spell and then a bunch of descendants that are spells (SpellFireball, SpellIcewall, etc) is the wrong way to do this, but I'm not sure how each spell can have different ranges and areas that aren't just numbers but instead are sets of tiles relative to the origin tile passed in. I've been learning about delegate functions and feel like this is the direction I need to head in. Is this a good idea? <br><br> Thanks for reading and for any insight you can offer! design grid based game delegate object-oriented-programming Fri, 15 Jun 2018 00:38:44 GMT dronus86 Networking attributes through interface Hello, I have my WeaponControl script call functions in my weapons through IWeapon interface, but the problem is that I cannot use NetworkServer.Spawn(bullet); on my weapon, even with the [Command] attribute because I get error "NetworkServer is not active. Cannot spawn objects without an active server." Everything works fine on host side though. WeaponControl.cs public class WeaponControl : NetworkBehaviour { // Use this for initialization private IWeapon currentWeapon; void Start () { } // Update is called once per frame void Update () { if (!isLocalPlayer) { return; } if (CrossPlatformInputManager.GetButtonDown("Fire1" + tag)) { currentWeapon.CmdCharge(); } if (CrossPlatformInputManager.GetButtonUp("Fire1" + tag)) { currentWeapon.CmdFire(); } } public void Switched(IWeapon newWeapon) { Debug.Log("New Weapon"); currentWeapon = newWeapon; } } IWeapon.cs public interface IWeapon { void CmdFire(); void CmdCharge(); } Gun.cs public class GunController : NetworkBehaviour, IWeapon { public GameObject bulletPrefab; public Transform bulletSpawn; public double timeToMaxCharge; public float minCharge; public float maxCharge; public double cdAmount; private double timeStamp = 0; //cooldown private double chargeStart; private float charge; private bool onCd; public int parentIdShow; [SyncVar(hook = "CallbackSetOwner")] public NetworkInstanceId parentId; private WeaponControl weaponControl; // Use this for initialization void Start () { weaponControl = gameObject.transform.parent.gameObject.GetComponent<WeaponControl>(); weaponControl.Switched(this); //gameObject.transform.position = gameObject.transform.parent.Find("GunPosition").transform.position; } [Command] public void CmdCharge() { if (timeStamp <= Time.time) { onCd = false; } chargeStart = Time.time; } [Command] public void CmdFire() { if (!onCd) { double chargeTime = Time.time - chargeStart; double chargePercent = chargeTime / timeToMaxCharge * 100; charge = (float)maxCharge / 100 * (float)chargePercent; if (charge > maxCharge) { charge = maxCharge; } if (charge < minCharge) { charge = minCharge; } Debug.Log(charge); // Create the Bullet from the Bullet Prefab var bullet = (GameObject)Instantiate( bulletPrefab, bulletSpawn.position, bulletSpawn.rotation, gameObject.transform); // Add velocity to the bullet bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * charge; timeStamp = Time.time + cdAmount; NetworkServer.Spawn(bullet); } onCd = true; } } ... networking multiplayer-networking object-oriented-programming Thu, 09 Nov 2017 21:53:07 GMT Topsu Duplicating GameObject with variations of the same functionality. I've written a script that extends the MonoBehavior class. It essentially turns a game object into a "beacon", which can be selected, moved towards, etc. Each beacon should have unique properties like a name and other such information. I'm new to Unity and unsure of how to do this, but how would one reuse that script and still give each object unique properties? In other object-oriented languages, we create instances of a class with a constructor, which takes care of my problem because the unique values can be specified there, but I'm not sure how to do the equivalent in Unity (C#) since I'm just creating a new game object, placing it on the map, and attaching my script to it. Thanks! scriptingbasics oop object-oriented-programming Thu, 20 Apr 2017 18:32:21 GMT nsempere Unity Inheritance and Monobehaviour Hi, I have three classes 'Building', 'Residential' and 'Business'. The 'Building' class does not inherit from anything and the 'Business' and 'Residential' classes inherit from the 'Building' class, which specific functionality added to each based on the type of building, so for instance the 'Business' class has methods to calculate profit. I have just created a 'Bank' class which inherits from monobehaviour so i can attach it to the bank model gameobject but i want it to inherit the functionality from the 'Business' class. I have never really used OO programming with unity, whats the best way to structure my classes for inheritance ? gameobject inheritance monobehaviour object-oriented-programming super Sat, 24 Sep 2016 15:05:53 GMT GamesDeveloper12 (C#/OOP) Accessing one public function belonging to multiple gameObjects? I'm facing a bit of an OOP dilemma and would greatly appreciate any help. My current situation is this: I'm designing a horizontal SHMUP and the player's ship shoots lasers. I've given the lasers collision detection so that when they collide with anything tagged as "Enemy," the player's score is increased and both the enemy and laser are destroyed. I've since decided to add a second enemy, and that's where I've encountered problems. Rather than copy--paste the code from the first enemy's script, I decided to muck around with OOP by creating a brand new script for the second enemy and having it inherit everything from the first one. In other words, the second enemy's script is now a child to the first enemy's. The problem I'm having is related to both enemies sharing identical functions, namely the "getValue" function, which is a public function that returns an integer storing how much the enemy is worth when destroyed. (This is especially true since I've made the second enemy worth more than the first one.) The laser calls the "getValue" function when it makes contact with enemies. My plan is to have the laser (or rather its script) do most of the dirty work by calling public functions belonging to other gameObjects. For example, it grabs the score from the enemy's "getValue" script, then increases the player's score by calling an "increaseScore" function belonging to the player's ship's script. Here's an example of the laser's code in which it calls the enemy's "getValue" function: void OnCollisionEnter(Collision other) { if (other.gameObject.CompareTag("Enemy")) { float score; // Get how many points the enemy is worth score = other.gameObject.GetComponent<Enemy1Script>().getValue(); // Give the player as many points as the enemy is worth player.GetComponent<PlayerScript>().increaseScore(score); // Destroy both the enemy and laser Destroy(other.gameObject); Destroy(this.gameObject); } } My specific problem is this: How am I supposed to make the code on line 7 (score = . . .) also apply to the second enemy if I must specifically type the name of the enemy's script in GetComponent? The first enemy's script is named Enemy1Script and the second enemy's is Enemy2Script, but I can only enter one, even despite the fact that both scripts share the same "getValue" function! In other words, I want to access the "getValue" function *regardless* which enemy (or enemy's script) it belongs to; but I seemingly can't. I understand that I could use a series of If--Then statements to take different actions based on the gameObject's name. For example, if its name were Enemy1, Enemy1Script's "getValue" would be accessed via GetComponent. If it were Enemy 2, then Enemy2Script's "getValue" would be accessed. But to me that seems like a long-winded way of doing it and would, at least in my opinion, almost defeat the purpose of using tags! Is there any other way to get around this besides a series of If--Then statements like I described? Am I perhaps going about this the wrong way by having the lasers handle everything by calling public functions themselves? Again, I would greatly appreciate any help. Thank you in advance! c# collision gameobjects functions object-oriented-programming Fri, 23 Oct 2015 12:22:33 GMT Chubzdoomer Creating a switch for checking if a GameObject has a Script attached Hey Community, I am trying to create a way to manage a mouse click in one class. Depending on what kind of GameObject is clicked: the object will do an action. I am planning on making Clickable Objects into an interface all containing a clickedOn() method, but I've been wrapping my head around the possibility of a Switch/Case statement that checks if a GameObject contains specific Scripts. The switch statement will then do an action depending on what kind of Script it finds on the object. gameobject object-oriented-programming Sun, 06 Sep 2015 03:12:20 GMT chomps32 How exactly do Monobehaviour functions work? So I've used functions like Awake, FixedUpdate, OnTriggerEnter and whatnot for some time now, but I'm not sure I fully understand how those functions work on a larger scale. I notice that they don't need to be tagged as "new" or "override". And it will compile and function properly regardless of whether one of these functions is actually implemented in a custom script. What's going on with these functions, exactly? How do these built-in functions fit into the larger picture of object-oriented programming? class monobehaviour functions implementation object-oriented-programming Mon, 03 Aug 2015 22:47:18 GMT Nemox trying to update the guiText.text component only when required im getting the following error when im tyring to call a very specific function only when required so that i can update the HUD rather then doing a call every frame Player.cs(61,47) error CS0120: An object reference is required to access non-static member `UnityEngine.Component.guiText' player player1 = new player(); void updateHUD() { this.guiText.text = "Health: " + player.CalculatePlayerHealth (0,0); } if anyone can fix my code id be greatful and ive looked everywhere for an answer... cs0120 object-oriented-programming Thu, 25 Dec 2014 18:46:29 GMT bot-93 Polymorphism and interfaces So I have two set of game objects: Damage Dealers and Damage Takers. The former implements this interface: public interface IDamageDealer { int Damage { get; set; } } The latter implements this one: interface IDamagable { void hitReg(IDamageDealer dd); } In the OnCollisionEnter methods of the DamageDealers I want to deal damage to a Game Object if it is a Damage Taker without knowing exactly what type of Damage Taker it is. So I added a specific tag to the Damage Takers and tried to get their script component which implements the interface `IDamageDealer`: void OnCollisionEnter(Collision collisionDetails) { GameObject other = collisionDetails.gameObject; if(other.tag == Constants.DAMAGABLE_TAG) { other.GetComponent<IDamagable>().hitReg(this.damage); } ///... } This does not work since in Unity the type parameter of this method call must be of type `UnityEngine.Component. **Is there a generic built in way to deal with this situation un Unity?** In the meantime I added an extension method to solve my problem. I hope it helps someone: public static class ExtensionMethods { public static T GetComponentByInterface<T>(this GameObject go) where T : class { T ret = null; foreach (var component in go.GetComponents<MonoBehaviour>()) { T current = component as T; if(current != null) { if (ret == null) ret = current; else throw new Exception(); // TODO: OWN EXCEPTION } } return ret; } } gameobject interface object-oriented-programming Tue, 09 Dec 2014 00:30:08 GMT VSZM Every active Object a Script? no some efficient way? I have 5 Objects Patrolling same, but in various directions . the simple way is to create 5 different scripts and attach them one by one to objects. I mean 5 different script for just a simple difference in direction ? seems annoying. is there an easier, Efficinet way to make 1 script and customize it for specific objects? something like Inheritence in class programming ? and another question. where i should define a public class, to derive from it in scripts ? in another script ? class object object-oriented-programming Thu, 05 Jun 2014 09:23:06 GMT VoidScreamer How do you debug arrays of objects? I'm trying to debug this script to see if it is actually creating an array of cards with real values. I gave the deck a debug function that prints the amount of cards and, supposedly, the card values. With this setup, newDeck.debug() will return > 52--singleCard,singleCard,singleCard..... *Updated code will return error > (138,74): BCE0019: 'cardToString' is not a member of 'Object'. #pragma strict // Based off of a tutorial by Mike Hall on function Start () { var newDeck = new Deck(); // newDeck.stack(1); newDeck.debug(); } function Update () { } class singleCard { var rank : int; var suite : String; var cardRank; var cardSuit; function singleCard (cardRank, cardSuit) { this.rank = cardRank; this.suite = cardSuit; } function cardToString () { switch (this.rank) { case 0 : cardRank = "Ace"; break; case 1 : cardRank = "Two"; break; case 2 : cardRank = "Three"; break; case 3 : cardRank = "Four"; break; case 4 : cardRank = "Five"; break; case 5 : cardRank = "Six"; break; case 6 : cardRank = "Seven"; break; case 7 : cardRank = "Eight"; break; case 8 : cardRank = "Nine"; break; case 9 : cardRank = "Ten"; break; case 10 : cardRank = "Jack"; break; case 11 : cardRank = "Queen"; break; case 12 : cardRank = "King"; break; default : cardRank = null; break; } switch (this.suite) { case "C" : cardSuit = "Clubs"; break; case "D" : cardSuit = "Diamonds"; break; case "H" : cardSuit = "Hearts"; break; case "S" : cardSuit = "Spades"; break; default : cardSuit = null; break; } if (cardRank == null || cardSuit == null) { return "Null Card"; } else { return cardRank + " of " + cardSuit; } } } class Deck { var cardDeck = new Array(); var n; function stack (n : int) { var ranks = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"); var suits = new Array("C", "D", "H", "S"); var i : int; var j : int; var k : int; var m : int; m = ranks.length * suits.length; // Set array of cards. this.cardDeck = new Array(n * m); // Build Array for (i = 0; i < n; i++){ for (j = 0; j < suits.length; j++){ for (k = 0; k < ranks.length; k++){ this.cardDeck[i * m + j * ranks.length + k] = new singleCard(k, suits[j]); } } } } function debug () { var stringDebug : String = "Deck--"; var i : int; for (i = 0; i < cardDeck.length; i++){ stringDebug = stringDebug + " || " + cardDeck[i].cardToString(); } Debug.Log(stringDebug); } } javascript array objects object-oriented-programming Wed, 07 May 2014 01:38:09 GMT CoreyNW How can I pause one object's Update() until another class has performed its task? I'm struggling making an RPG turn-based battle system (à la early Final Fantasy), and I'm really trying to take an object-oriented approach. I have a CombatManager class attached to an object that takes all the combatants, sorts them according to each combatants' Speed stat, and tells each combatant when he can act. However, I've run into a problem on that last part: How do I tell the CombatManager to stop its job for a moment so the combatant can do his job? If the combatant is the player, the program will pause and wait for input, and this could take many frames, during which the CombatManager shouldn't do anything. Telling the player to act is simple enough (just call the player's Act() method), but how do I pause the CombatManager then resume it when the player is done? Upon request, here is my CombatManager. There is still much work to be done on it. public class CombatManager : MonoBehaviour { private List<Combatant> combatants; private Queue<Combatant> combatantsQueue; private bool isRunning; private void Awake() { combatants = new List<Combatant>(); combatantsQueue = new Queue<Combatant>(); isRunning = false; } private void Update() { while(isRunning) { // Run the combat. // Dequeue a combatant and tell it to act. // Add it back to the queue (at the end). // When it's done acting, CombatManager should be notified so it can dequeue the next combatant. // If a combatant is unable to act (such as when he dies), remove him from the queue. // Other combatants may revive him, in which case add him back to the queue. } } public void AddCombatant(Combatant combatant) { combatants.Add(combatant); } public void SortCombatants() { // Sort combatants by speed, highest first combatants = combatants.OrderByDescending(c=>c.Speed).ToList(); foreach(var c in combatants) { // Add each combatant to the queue, starting with the fastest. combatantsQueue.Enqueue(c); } } public void StartCombat() { SortCombatants(); isRunning = true; } } PS - Any general tips on creating an RPG turn-based battle system would be greatly appreciated, as well. I'm having a tough time conceptualizing the design taking into consideration the game loop. rpg turn-based battle-system object-oriented-programming Tue, 22 Apr 2014 06:29:50 GMT JDCAce55 Loot code Modification Hi guys, I'm an artist making a demo level with some of my assets. I've been "programming" (following tutorials) for like two weeks now so I only know enough to make slight modifications to code. The following works, but I'd like to add functionality, which is a little beyond what I'm capable of right now.. I don't expect anyone to write anything for me, but some solid guidance would be greatly appreciated! First, where would I stick a Random.Range in here? I'd like to enter my entire loot table into the array and have the script choose from the items. Second, how would I tell it to only drop a specific number (or even better, a random range) of items. using UnityEngine; using System.Collections; using System.Collections.Generic; public class ItemDropper_Death : MonoBehaviour { public List<GameObject> objectsToDropOnDeath; public int offSetWidth = 10; public void AddItemToDrop(GameObject newItem) { if (newItem != null) { if (!objectsToDropOnDeath.Contains(newItem)) { objectsToDropOnDeath.Add(newItem); } } } public void OnDeath() { if(objectsToDropOnDeath.Count > 0) DropItems(); } private void DropItems() { foreach (GameObject myObject in objectsToDropOnDeath) { if(myObject != null) InstantiateNewObject(myObject); } } private void InstantiateNewObject(GameObject objectToDrop) { Instantiate(objectToDrop, GetPosition(), GetRotation()); } private bool offsetLeft = true; private Vector3 GetPosition() { Vector3 newPosition = new Vector3(); int randX = (int)Random.Range((offSetWidth / 1.5f), offSetWidth); int negRandX = (int)Random.Range(-offSetWidth, -(offSetWidth / 1.5f)); int xOffset = 0; if (offsetLeft) xOffset = negRandX; else xOffset = randX; offsetLeft = !offsetLeft; newPosition = new Vector3(this.transform.position.x + xOffset, this.transform.position.y, this.transform.position.z); return newPosition; } private Quaternion GetRotation() { Quaternion rot = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f); //rotation of 0, needed for instantiation return rot; } } c# basic programming general programming object-oriented-programming Mon, 31 Mar 2014 15:01:29 GMT Maligma Any programs to practice javascript? Hello all, is there any freeware programs to try small bits of javascript code b'coz recently i downloaded a pdf book called javascript bible. and i need to try those codes in a program to see how it works. or is there any way i can do this in unity 3d? Thanks, Rakesh. basic programming general programming object-oriented-programming Sat, 22 Mar 2014 08:21:34 GMT RakeshB.B Change the size of an object, but only one side Hello and thank you, When I used to program in XNA in 2d,I could draw an image using a rectangle with the inputs of x, y, height, width. Now, using unity, if I shrink the Y scale, it takes pixels off both sides of the object. This makes the object appear to raise up. Is there a way to shrink an object, but just from the top? object-oriented-programming Sat, 08 Feb 2014 10:37:33 GMT LeonineStudios How to make a top down field of view similar to Monaco I'm working on a 2D top down game, that's supposed to be stealth oriented, but I don't know how to make it so you can't see what's on the other side of walls/corners/etc, similar to [Monaco's style][1], where you can only see whats immediately around you, everything is covered in a sort of fog. [1]: field of view property fields object-oriented-programming Mon, 23 Dec 2013 17:18:52 GMT JackieKan Events vs GetComponent for inter-script functionality I have seen many questions here having answers that give example on how to use `GetComponent` in order to modify a value in another script, or to call a function on another script. This is pretty much the same thing as passing a reference to another object during the contructor of your object, giving it full reign over that other object. Now, I'm no programming expert but this bothers me because to me this seems like it's breaking encapsulation. Your script now has to be aware that the other script exists. This means your script cannot work independently of the other script. This is probably not a big deal on small projects, but I can see this leading to a giant mess with all scripts being intra-dependent on each other to the point where the project won't even compile should a single script be removed out of the equation. I would have thought that a safer and more efficient way to make your classes work with each other would be to use events. This way, two classes that communicate with each other can exist without knowing of each other, and still compile and work (without the communication functionality) should one class be unaccessible. So why is `GetComponent` seems to be the most popular answer for questions related to "how do I make my script affect this other script?" type questions? encapsulation object-oriented-programming Mon, 16 Dec 2013 20:08:15 GMT guitarxe