_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
How can this method to make a text mesh always face the camera be simplified? (Unity c ) Despite a fairly heafty new years I am back trying to learn a bit more coding D This latest feature I am trying to add is a TextMesh that floats above a gameobject when the player is looking at it. I does all work fine (except it kinda shakes a little but I'll look into that another time). But as I wrote the method to make the textMeshObject look at my camera, I just had a niggling feeling it could be written in less lines of code. I actually get this a lot where I write several lines and think it must be able to be simplified, and after the code having several parts like this it can look pretty messed up. Anyways, I thought i'd ask you experts on here if it was possible to do this an simpler (NOTE I only want it to rotate on Y Axis) void FaceTextMeshToCamera() Vector3 origRot textMeshObject.transform.eulerAngles textMeshObject.transform.LookAt(textLookTargetTransform) Vector3 desiredRot textMeshObject.transform.eulerAngles desiredRot.x origRot.x desiredRot.z origRot.z textMeshObject.transform.eulerAngles desiredRot
|
0 |
How can i use StartCoroutine to set the speed for each scaling step of the walls? using System.Collections using System.Collections.Generic using UnityEngine public class WallsTest MonoBehaviour using a GameObject rather than a transform public GameObject prefab public Vector3 wallsStartPosition public float width 0 public float height 1 public float length 2 public Camera wallsCamera void Start() wallsCamera.transform.position new Vector3(wallsStartPosition.x, wallsStartPosition.y 100, wallsStartPosition.z 235) StartCoroutine(BuildWalls()) IEnumerator BuildWalls() for (int i 2 i lt 2 i ) GameObject go Instantiate(prefab) go.transform.parent transform Vector3 scale Vector3.one Vector3 adjustedPosition wallsStartPosition float sign Mathf.Sign(i) if ((i sign) 2 0) adjustedPosition.x (length sign) 2 yield return new WaitForSeconds(0.1f) scale.x width scale.y height scale.z length width else adjustedPosition.z (length sign) 2 scale.x length width scale.y height scale.z width adjustedPosition.y height 2 go.transform.localScale scale go.transform.localPosition adjustedPosition What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them. But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.
|
0 |
Global variables in a multiplayer environment I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like private string arrivalOrder void playerArrived(string playerName) arrivalOrder arrivalOrder.getLength() 1 playerName I would like to know how to do in a multiplayer environment. How the client can communicate to server "my player finishes the racing"? Thanks
|
0 |
Delay in connecting to server in Unity I have a button, when I press the connect button, it gets connected to the server. When I press the connect button again, it's getting delay in connecting to the server. Below is the code to connect to the server public void setupSocket() try socket new Client(Host, Port) theStream socket.GetStream() theWriter new StreamWriter(theStream) theReader new StreamReader(theStream) socketConnect true catch (Exception e) Debug.Log("Socket error " e) And I have one more issue. When I take the desktop build of the app and opened the app, clicked button, it's getting connected to the server, but when I click the button again it's not getting connected. But when I close the app, it displays the connection message and also close message on the server. Is there anything to be set when taking the desktop build? Can anybody help out what will be the problem?
|
0 |
Make a 2d top down game with round map Currently, I am making a top down game using Unity. Here is the problem that I m trying to solve The player in my game is always centered on the screen, and the since the map is rounded, the agents controlled by AI must acts and be shown base on the distance of the round map. Here is the sketch for the better explanation. I want to ask for a good way to design and implementing the above task. And here is my approach for this task I split the map into 4 areas (could be smaller and more in number). Each of the 4 areas will have its corresponding area outside of the map area (The outside map areas are trigger boxes). When the area that is covered by the main camera has its parts out of the map area, these outside parts will active the trigger boxes that are overlapped by them. When a trigger box is activated, all the agents in its corresponding area inside the map will be moved temporally to the trigger box area. This can be done just by adding the difference between the trigger area position and the inside map area that the agent is staying to the agent s position. When the area that is covered by the main camera no longer overlap the trigger box, all the agent will move back to its corresponding position inside the map. This process is done by reversing the moving out process. Here is the sketch for this. And the flawless come when there are agents with the flocking or forming formation behavior that requires the agents to have connections with others. When an agent is moved out of it actual position, the other agents in the formation will lose their connection with the moved agent (Like the distance between them suddenly becomes large). I think that this could be somehow solved by storing the actual position of the agent and marking it as moved, but it may be too computational cost, or having too many cases. I tried to think of a different approach, that the map border is a circle, and to show the round view is just needed to take the symmetric through the center of the map. However, the circular border shows a bad animation when the agents try to move through the border. (I don't have enough reputation attach image about the flocking behavior problem and the circular approach, so you have to imagine it) If you can solve the problems that I mentioned above or have a different approach, please show me. Thank you.
|
0 |
Saving Unity Custom Inspector state to a text save file? For the basic values I know how to do it like Item name (Simple string value) Amount (Simple int value) isNormalDrop (Simple bool value) The problem is saving the Reflection variable (The script part near the bottom) which is of type 'UnityEngine.Object' and the GameObject variable how would I do this?
|
0 |
2D UI Image with 1px border randomly gets different thickness I created a test image that is 60 x 60 px, which has a 1px border. I then drop that into Unity as a UI sprite image set to the same size, however the 1px border on a few sides can appear to be thicker, and this ruins the look I am going for especially when there are multiple of them. I've tested in the editor and creating builds (testing resolutions), and the same issue in all cases. It's easier to explain this with images. The left screen shot is the actual size of the image in the game view. The zoomed in image is another case where the borders change thickness, but zoomed in to make it more clearer. I've tried various settings, always the same issue. How can I get the image to appear exactly as it should with no changes to the borders?
|
0 |
Unity polymorphism in editor through a list So I have an ItemDatabase class which basically only has a list of Item public class ItemDatabase MonoBehaviour public List lt Item gt Items new List lt Item gt () The Item class looks as follows System.Serializable public class Item public string Name public int Id public string Description public Texture2D Icon Now I have some item types deriving from the Item class, for example Consumable System.Serializable public class Consumable Item public int Resore I next created a gameobject (empty) in my editor and hooked up my ItemDatabase to that object, providing a number of items in the list is no problem but I would like to make sure that from my editor I can choose a type of Item to put into the list, as of now, it only lets my add Item and not Consumable because it is a list of Item. Can I also force the editor not to accept just Item by making it an abstract class?
|
0 |
How to calculate FPS and what factors affect FPS? In this case, FPS means Frames Per Second and that means the number of frames that graphic hardware render in one second. I'm wondering what kind of stuffs could affect FPS? So, for some tests I created a simple scene in Unity with some cubes and capsules and then create a empty game object and then add this c code to it public class FPSReport MonoBehaviour public double Fps void Update () Fps 1.0 Time.deltaTime I think it can tell me the FPS. When I played it it worked but it wasn't more than 30. I was saw a lot of games that their fps was normally on 150. Is this fps rate ok? If I add more objects, textures, animations , etc ... to my scene. What happen to my fps? Could it attain zero? and If it attain zero, what is the meaning of a zero FPS (the hardware stopped working?!)?
|
0 |
Tab between input fields I am new to working with Unity3d, I need to navigate between several inputField, for this I have looked at the solution that is in tab between input fields, but always the FindSelectableOnUp() or FindSelectableOnDown() returns null, so my next is always null and always ends in next Selectable.allSelectables 0
|
0 |
In unity, some part of mesh doesn't show only in play mode This is screenshot of not playing mode. You can see the the speedloader and bullets inside of the revolver. And this is when playing mode. As you can see, I can see the speedloader and bullets in scene view, but not player's camera. Sometimes, it disappears in scene view either! I made this model same as other weapons, but others are working fine. Only this weapon causes this problem. All weapons that I made are based on same model and rigs, and I kept the weapon's scale fit as same as possible. I tried move the camera and scale down a little bit, but still couldn't saw. Why this is happening? How do I solve this? Any advice will very appreciate it.
|
0 |
Unity Shader Graph randomly tiled sprite Lets say I have a shader with a clean white tile. Then I use it on a wall and tile it a few times. I also have a sprite with numbers. Now, is it possible and if yes how. To put a random sprite number ontop of the already tiled texture. Example I am pretty sure this can be achieved with shadergraph, but I am hardly an expert and I really dont want to spend a month or more try erroring my way through...
|
0 |
Multipurpose buttons As in the title, I am trying to figure out how to use a button for multiple purposes in Unity. In my specific case for instance, I am currently using the joystick button 0 (the A button) to perform a simple melee attack if (Input.GetButtonDown( quot Fire1 quot ) amp amp currentState ! PlayerState.attack amp amp currentState ! PlayerState.stagger) second clause because I do not want to indefinitely attack every frame StartCoroutine(GetComponent lt Player Melee gt ().FirstAttack()) In the conditions I make sure that I am pressing the right button and determining in which state my player is (the state is then changed in the attack coroutine). In order to interact with a given object, I created a trigger to check that the player is within range to inspect the object if (Input.GetButtonDown( quot Interact Alt quot ) amp amp playerInRange) if (dialogueBox.activeInHierarchy) dialogueBox.SetActive(false) else dialogueBox.SetActive(true) dialText.text dialogue In the Input manager settings in unity, I set the 'Interact Alt' button to be the same as the 'Fire1' used in the attack script. The scripts actually work, however whenever I check an object I also perform an attack. How can i make so that when I want to inspect an object I do not attack? I was considering create a new finite state similarly to the one I use to attack e.g. 'PlayerState.interact', but then I was wondering, how would unity give the priority to which command to use? Another alternative would be to check if I am in the range of some object when I want to attack and if within range it inspects the object instead, but it seems to me a much more convoluted solutions. How should I solve this?
|
0 |
Unity stats framerate vs Time.deltaTime Googling around, a way for calculating framerate and displaying it as text ingame is using 1 Time.deltaTime. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If 1 Time.deltaTime is incorrect, how does one go about calculating FPS? Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60.
|
0 |
Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice!
|
0 |
How can I generate spheres equal between the waypoints? public void duplicateObject(UnityEngine.GameObject original, int howmany) howmany for (int i 0 i lt waypoints.Count 1 i ) for (int j 1 j lt howmany j ) Vector3 position waypoints i .transform.position j (waypoints i 1 .transform.position waypoints i .transform.position) howmany UnityEngine.GameObject go Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity) go.transform.localScale lightsScale objects.Add(go) For example howmany value is 21. If I have two waypoints it's fine it will create 21 spheres between the two waypoints. But if I have 3 waypoints it's creating 42 spheres but it should create 21 since howmany is still 21. And it also position the spheres between waypoint 1 and 2 and then from waypoint 2 to 3. But I want that it will create 7 spheres between waypoints 1 and 2 and 7 spheres between waypoints 2 and 3 and last 7 spheres between waypoints 3 and 1.
|
0 |
How can I use GPL software like Stockfish Chess Engine in my Unity game? I am working on a 3D Chess game and I want to implement an A.I bot to play with the player. I found a chess engine called Stockfish which serves this purpose, and I would like to implement that engine in my project. Is it as simple as including the Stockfish code in my project or importing a binary as a plugin, or do I have to do something more complex because of the GPL licence?
|
0 |
How best to structure manage hundreds of 'in game' characters I've been making a simple RTS game, which contains hundreds of characters like Crusader Kings 2, in Unity. For storing them the easiest option would be to use scriptable objects, but that isn't a good solution as you cannot create new ones at runtime. So I created a C class called "Character" which contains all data. Everything is working fine, but as the game simulates it constantly creates new characters and kill some characters (as in game events happen). As the game continuously simulates it creates 1000s of characters. I added a simple check to make sure a character is "Alive" while processing its function. So it helps performance, but I can't remove "Character" if he she is dead, because I need his her information while creating the family tree. Is a list is the best way to save data for my game? Or it will give problems once there are 10000s of a character created? One possible solution is to make another list once the list reaches a certain amount and move all dead characters in them.
|
0 |
One Android app, dynamic load several Unity games I'm a newbie in this unity world, exciting about everything in it. Days ago I came up with this idea One day someone finds this android app, naming "Blahblah Game Engine" or anything else. This app has to be very small, containing only some simple activity and Unity runtime, without further resources related to any specific game. He installs it and sees an android activity, maybe a webview, showing a list of unity games the server currently hosting, produced by the very same Blahblah company. Then he clicks on one and this "Blahblah Game Engine" loads the game build via network, starts an Unity activity, without prompting an installing dialog. He can exit the current game whenever he likes, returns to the previous game list, and plays another, all working well in one app's lifetime. In a word, the user experience is very much like how we play games on www.kongregate.com with pc browsers light weight app, mutiple games in one list, all loads via network, playing right away and installing less. Any game that listed in this app should not be installed as a standalone android app, it should be part of the "Blahblah Game Engine", stored as a file inside data folder of "Blahblah Game Engine", run as an activity of "Blahblah Game Engine". Is it possible with Unity 5, both technically and legally? If I were to start this "Blahblah Game Engine" project, should I choose Unity 5 personal or pro licence?
|
0 |
Health Bar is always 100 full I have this GUI to graphically display a variable similar to the health in a game. The variable 'test' goes up and down during gameplay. To show this I have the following onGUI () public GUISkin btnskin1 public Texture2D emptyTex public Texture2D fullTex public Vector2 pos new Vector2(20,40) public Vector2 size new Vector2(60,20) void OnGUI() float test GUI.skin btnskin1 if (LoadDiagram.diagramaCarga.TryGetValue (TimeManager.gametime, out test)) GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y)) GUI.Box (new Rect (0, 0, size.x, size.y), emptyTex) draw the filled in part GUI.BeginGroup (new Rect (0, 0, size.x test, size.y)) GUI.Box (new Rect (0, 0, size.x, size.y), fullTex) GUI.EndGroup () GUI.EndGroup () In the game scene I attached the empty bar to the emptyTex texture, and the full bar to the fullTex texture. When I play the game, he bar is always full. I have not inserted the minimum and maximum of the variable test because I don't know where, but I guess that may be necessary. Any hints?
|
0 |
How can I start the game with a random formation? public class SquadFormation MonoBehaviour enum Formation Square, Circle, Triangle Header("Main Settings") public Transform squadMemeberPrefab public int columns 4 Range(4, 100) public int numberOfSquadMembers 20 public float yOffset 0 Range(1, 20) public int numberOfSquads 1 Space(5) Header("Formations") public int squareSpace 10 public int circleSpace 40 Range(3,50) public float moveSpeed 3 public bool randomSpeed false Range(3, 50) public float rotateSpeed 1 public float threshold 0.1f public bool destroySquad false public string currentFormation public bool startRandomFormation false private Formation formation private List lt Quaternion gt quaternions new List lt Quaternion gt () private List lt Vector3 gt newpositions new List lt Vector3 gt () private bool move false private bool squareFormation false private List lt GameObject gt squadMembers new List lt GameObject gt () private float step private int randomSpeeds private int index 0 private int numofobjects 0 Use this for initialization void Start() numofobjects numberOfSquadMembers if (startRandomFormation) formation UnityEngine.Random.Range(1, 3) In this case I have 3 formations. But it might later more or less formations. Making this line is has no sense formation UnityEngine.Random.Range(1, 3) The idea is to start randomly with one of the 3 formations. How can I get the number of formations ? The count in the enum ? And how can I select randomly one formation ?
|
0 |
Is there a way to make GUI.SelectionGrid expand horizontally I am working on an inventory system, And I want to be able to make a Selection Gird that expands horizontally rather than vertically, is there an easy way to do this? Or will I have to create my own version of SelectionGrid?
|
0 |
score and high score system for multiple levels I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far public class ScoreIncrease MonoBehaviour public Text scoreTxt public int score void Start() LoadScore() void Update() if (Input.GetKeyDown(KeyCode.Space)) Save() public void Save() score scoreTxt.text "Score" score BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Create) ScoreContainer scoreContainer new ScoreContainer() scoreContainer.score score bf.Serialize(file, scoreContainer) file.Close() public void LoadScore() if(File.Exists(Application.persistentDataPath " scoreContainer.dat")) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Open) ScoreContainer scoreContainer (ScoreContainer)bf.Deserialize(file) file.Close() score scoreContainer.score scoreTxt.text "Score" score Serializable public class ScoreContainer public int score How can I change this so that each level has a separate highscore and all levels have a start score of 0?
|
0 |
How can i detect if the player is inside an explosion radius? I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something. What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?
|
0 |
Screen transition effect like subway surfers I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent. https www.youtube.com watch?v Muh7QFisCfE t 01m57s
|
0 |
import text strings into Unity editor 3D text objects so that Scene View displays them I am having trouble finding a solution to this problem. I want to generate the text for TextMesh.text in a custom application and import into the Unity editor so that I can then scale the text to fit. If anyone could point me in the right direction to simply edit a 3D Text game objects' text mesh.text property from a script so that it is reflected in the scene view in Unity's editor, I would greatly appreciate it! Best Regards, Ben
|
0 |
Select specific tile in Tilemap I am following this video tutorial on how to implement drag to select behavior like in an RTS. The only difference is, I'm using a tilemap. The selection area is a square which I can drag to make it as big as I want, like in any top down RTS. CodeMonkey in his video uses Physics2D.OverlapAreaAll to get a list of all colliders in the selected area. I want to use this to specifically see which quot vegetation quot tiles I've selected. However, no matter which vegetation tile I select, or how many, I always get one result the vegetation tilemap itself. You can clearly see from this picture that every grass tile and every tree tile have a collider around them, which is why this works, but how can I get exactly those that I selected? Other than vegetation from the tilemap, I also want this to work with GameObjects that have Box2DColliders on them, and that works out of the box. I also made those MonoBehaviors inherit an interface called ISelectable, so I can only add to the selected list entities that have that inherit that interface. I tried to do the same with vegetation like so public class Vegetation Tile, ISelectable but it doesn't work. What am I missing? Can this even work on a specific tile basis?
|
0 |
why is GetComponent returning null? As you can see in the attached image below and the code, I have added a class that implements the interface ICameraControl attached to a GameObject. When I call var controller GetComponent lt ICameraControl gt () , I get nothing returned (null), as in this example public class KeyboardHandler MonoBehaviour private void Start() var controller GetComponent lt ICameraControl gt () if (null controller) print("no ICameraControl found!") And the output is like this in the unity console no ICameraControl found! UnityEngine.MonoBehaviour print(Object) Assets.Player.KeyboardHandler Start() (at Assets Player KeyboardHandler.cs 18) Here's the Camera Position Handler attached to my game object Here's the interface implementation public class CameraPositionHandler MonoBehaviour, ICameraControl private GameObject mainCamera private Quaternion homePosition private void Start() mainCamera GameObject.FindGameObjectWithTag("MainCamera") homePosition mainCamera.transform.rotation private void LateUpdate() Any ideas what I am doing wrong? Much appreciated ) Matt Edit The keyboard script is on my player object (at bottom of the picture of the player object). And the Camera Position Handler is on the Camera Arm object. The Player object and Camera Arm objects are at the same level.
|
0 |
The best way to pass data between clients in a room I am developing a backgammon game in Unity and tried to use Photon. But I could not find a step by step help for it and I also know that photon in real time and it syncs data over 10 times per second. but I need to sync data after each moves. Would you please show me the best way to do that.
|
0 |
Unity Unable to take screenshots in server build I am trying to take snapshots in the server build of my Unity application. But the output image is all grey. From this post, I read that in headless mode, calling camera.Render() is necessary for rendering. I changed my screenshot logic accordingly. Here is my script private IEnumerator TakeSnapshot() yield return new WaitForEndOfFrame() var tempTexture RenderTexture.GetTemporary(Screen.width, Screen.height) camOV.targetTexture tempTexture camOV.Render() var tex new Texture2D(tempTexture.width, tempTexture.height, TextureFormat.RGB24, false) Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, tempTexture.width, tempTexture.height), 0, 0) tex.Apply() RenderTexture.active tempTexture Encode texture into PNG var bytes tex.EncodeToPNG() snapshotBase64 Convert.ToBase64String(bytes) File.WriteAllBytes( quot Users varun Desktop quot Time.time quot .png quot , bytes) Destroy(tex) I initalize the camera in the Start() method camOV Camera.main This works fine inside the editor but once I create a server build for Mac and try to run it I get this error. ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame. 0 ??? 1 operator delete (void , std nothrow t const amp ) 2 operator delete (void , std nothrow t const amp ) 3 operator delete (void , std nothrow t const amp ) 4 operator delete (void , std nothrow t const amp ) 5 (Mono JIT Code) (wrapper managed to native) UnityEngine.Texture2D ReadPixelsImpl Injected (UnityEngine.Texture2D,UnityEngine.Rect amp ,int,int,bool) Can someone give any suggestions? Thanks!
|
0 |
In Unity, how can I check if an input was made x seconds frames ago? I'm using the Rewired input plugin, and it comes with an input buffer. I enabled the buffer for my directional keys and airdash button so that the player doesn't have to hit both keys on the same frame in order to dash. However, this means that if you press both keys and hold them down for more than a frame, the airdash code gets run again. I tried to stop this by comparing Time.time at the beginning of Update() to Time.time at the beginning of the coroutine, but this seems inconsistent and it doesn't feel like the right way to do it. How would you check for the player's input time and compare it to the time since some previous input? Here's a sample of the dash code within FixedUpdate() Dash if (grounded) dashCount 0 dashTime 0 if (dashCount lt 2) print(currentTime dashTime) if (currentTime dashTime lt 0.1 dashCount 0) Double Tap Dash if (player.GetButtonDoublePressDown("Left")) StartCoroutine(Dash("left")) Button Dash if (player.GetButtonDown("Dash") amp amp player.GetButtonDown("Left")) StartCoroutine(Dash("left")) print(dashCount) and here's a sample of the coroutine Dash IEnumerator Dash(string axis) dashCount dashTime Time.time if (axis "left") if (inDash true) anim.SetBool("dashUp", false) anim.SetBool("dashDown", false) anim.SetBool("Hover", false) canControl false inDash true anim.SetBool("dashHorizontal", true) anim.SetBool("inDash", true) rigidbody2D.velocity new Vector2(rigidbody2D.velocity.x, 0) rigidbody2D.AddForce( dashForceHorizontal, ForceMode2D.Impulse) rigidbody2D.velocity Vector2.ClampMagnitude(rigidbody2D.velocity, maxVelocity) rigidbody2D.gravityScale 0 yield return new WaitForSeconds(0.2f) rigidbody2D.gravityScale 2 rigidbody2D.drag 25f yield return new WaitForSeconds(0.2f) if (grounded true) yield return new WaitForSeconds(0.1f) rigidbody2D.drag 0f canControl true anim.SetBool("dashHorizontal", false) anim.SetBool("inDash", false) inDash false yield break
|
0 |
Clamping the camera isn't so smooth when moving the camera around. Is there a way to make the clamping smoother? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook playerCameraCloseLook public CinemachineFreeLook playerCameraGameplayLook public float timeBeforeSwitching public float clampMin public float clampMax public float pitch public float speed private float brainBlendTime Start is called before the first frame update void Start() brainBlendTime Camera.main.GetComponent lt CinemachineBrain gt ().m DefaultBlend.m Time StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void LateUpdate() if (playerCameraGameplayLook ! null) pitch speed Input.GetAxis( quot Mouse Y quot ) pitch Mathf.Clamp(pitch, clampMin, clampMax) playerCameraGameplayLook.GetRig(1).GetCinemachineComponent lt CinemachineComposer gt ().m TrackedObjectOffset.y pitch IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) playerCameraCloseLook.enabled false playerCameraGameplayLook.enabled true PlayerLockManager.PlayerLockState(false) StartCoroutine(BlendTime()) IEnumerator BlendTime() yield return new WaitForSeconds(brainBlendTime) PlayerLockManager.PlayerLockState(true) I can look around up down left right using Cinemachine CinemachineFreeLook but when using the clamping in this script and then when moving the camera around with the mouse it looks like the camera is a bit stuttering jittering. Without the clamping, in the LateUpdate the camera will work fine but then I can't move the camera up down left right only to the left and right. The reason I'm trying to do the clamping on my own is that in the FreeLookCamera in the Axis Control gt Y Axis if I set the speed to 100 or 300 when I move the camera up and down it will also zoom in out on the player and I don't want that zooming but there is no option to remove disable the zooming.
|
0 |
Unity3D different object with the same mesh imported from Blender I would like to instantiate different objects (i.e. poker chips with different values) that actually share the same mesh imported from blender. To this end I have copied the assets and changed the texture but all the assets automatically switch to the last texture I choose as they are actually the same entity. What am i doing wrong?
|
0 |
Can I post to Facebook with my own text from Unity on behalf of the user? I'm using Facebook SDK for Unity 6.0 with FB.Feed. I'm trying to post a link to the user's feed, text and link on his behalf. So far I've managed to publish only a link and its details, the part where the user can write the post is left empty for him to fill.
|
0 |
How do I switch between different Update behaviour states in Unity? I have a bird entity that needs different update rules when it's moving or dying (among potentially other states). I want to avoid making my Update method a clutter of if else branches like this void Update() if(state movingState) Do moving logic. else if(state dyingState) Do dying logic. else if... Instead, I thought I could make a base class for all my bird behaviours, then derive classes for each state with their own update functions, and use the appropriate derived version based on the current state. public class BirdBaseModel MonoBehaviour void Update() ... public class BirdMoving BirdBaseModel void Update() ... public class BirdDying BirdBaseModel void Update() ... My BirdBaseModel is attached to the bird game object. Based on game states, I want to dynamically reference it in the GameController class. BirdBaseModel b if(State 1) b new BirdMoving() else if(State 2) b new BirdDying() Based on the above logic, I want to call the Update function of that particular class. How do I invoke the Update of the subclass?
|
0 |
How can I create a musical sheet using sprites?(Ocarina of time ) I am looking to make a musical sheet similar to the image below I want to use sprites prefabs have each sprite correspond to a different line Move down notes are more are being played have tail end notes disappear or go outside of text view (like when you type past a search bar) I am unsure if there is a UI asset in Unity that can perform what I just mentioned. I was thinking could just instantiate the prefabs in the right positions, shift them down, then delete the tail end prefabs as more are being played. Outside of that, I'm lost.
|
0 |
Why can changing a camera's position prevent it from rotating? I am going through the official introductory series "Roll a Ball" by the Unity team, and am on part 3 (youtube link. There is a ball with mouse controls attached, and a Camera set as a descendant of the ball so that it follows it around. As the tutorial mentions, the Camera at this stage "rolls" along with the ball and is unusable. The fix, as shown in the video, is the following added to Camera public GameObject player added through GUI private Vector3 offset void Start () offset transform.position player.transform.position void Update () transform.position player.transform.position offset I understand in terms of C syntax what this does, but I don't understand why it stops the camera from rotating. Isn't position controlled separately from rotation?
|
0 |
2D diagonal movement using Rigidbody2D I have a problem with 2d player movement, as I am unable to move on the Y axis. Yet, the movement on the X axis is working as intended. Below, you can see my code public Sprite directionUp public Sprite directionDown public Sprite directionLeft public Sprite directionRight public float speed 0.1f public byte direction 0 0 up, 1 right, 2 down, 3 left private SpriteRenderer spriteRenderer private Rigidbody2D rb2D private Sprite directionArray Use this for initialization void Start () rb2D GetComponent lt Rigidbody2D gt () spriteRenderer GetComponent lt SpriteRenderer gt () directionArray new Sprite directionUp, directionDown, directionLeft, directionRight if(directionArray 0 ! null) spriteRenderer.sprite directionArray 0 Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Keypad7)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad9)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.Keypad1)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad3)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.W) Input.GetKeyDown(KeyCode.Keypad8)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 0 else if (Input.GetKeyDown(KeyCode.S) Input.GetKeyDown(KeyCode.Keypad2)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 1 else if (Input.GetKeyDown(KeyCode.A) Input.GetKeyDown(KeyCode.Keypad4)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.D) Input.GetKeyDown(KeyCode.Keypad6)) rb2D.MovePosition(rb2D.position new Vector2(1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 By the way, please keep in mind I am quite new to Unity. EDIT 1 I have attached the entire script, some of the variables are unused right now(was testing other methods of movement). I tried to both Keypad 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off topic and I will look into it once I will get the Y axis to move). Thanks, Zryw
|
0 |
Leaderboard setup for Android I am totally new for this setup. I am trying to implement google Leaderboard. I followed the step by step process showed in "This Link". i opened windows Google play games setup Android setup. In Android setup i named the class name and copy and paste the xml code from play store account This Picture Shows this then i clicked setup button. i got two popup boxes, Shows below, in console i got messages Note All my software's are updated version only. first i used jdk 64bit. now i uninstalled 64bit and i installed jdk 32 bit. still i got the same problem Anybody Please help. Edit 2 using This video now i fixed the error JAVA HOME not set. then in unity i tried to do the same. Now it displays another message shown below
|
0 |
How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out?
|
0 |
Why won't my integer go down when my function is called? I'm trying to implement a limited use slow mo power into my game using C , but I can use it infinitely. Why won't my integer go down when my function is called? using UnityEngine public class TimeManager MonoBehaviour public float slowdownFactor 0.05f public float slowdownLength 2f public int slowmos 5 private void Update() Time.timeScale (1f slowdownLength) Time.unscaledDeltaTime Time.timeScale Mathf.Clamp(Time.timeScale, 0f, 1f) public void SlowMo() if (slowmos ! 0) Time.timeScale slowdownFactor Time.fixedDeltaTime Time.timeScale .02f slowmos using System.Collections using System.Collections.Generic using UnityEngine public class charcterMovement MonoBehaviour public TimeManager timemanager public Rigidbody rb public float forwardForce 1000f public float rightForce 100f public float leftForce 100f Start is called before the first frame update void Start() rb.useGravity true Update is called once per frame void FixedUpdate() rb.AddForce(0, 0, forwardForce Time.deltaTime, ForceMode.VelocityChange) Set Speed To Cube if (Input.GetKey( quot d quot )) rb.AddForce(rightForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot a quot )) rb.AddForce(leftForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot space quot )) timemanager.SlowMo()
|
0 |
Textures go black when changing Quality Settings at runtime Whenever I change my Quality Settings at runtime in editor mode or in build, all of my textures turn black. I use the following line to change the quality settings QualitySettings.SetQualityLevel(value, true) I have tried to set the boolean at false and it does the same result. I am using HDRP and the shader "HDRenderPipeline Lit" on pretty much all of my materials. There is an interesting fact, in editor mode, I just hover my mouse on any material inspector window, it updates all of my textures back to normal and solves the problem. Here is a screen showing the textures (left is normal, and right is bugged) Any idea ? Thanks.
|
0 |
How to execute a code from many scripts I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script. I need something like a function that i can call from any script and it calls the function from C. Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want.
|
0 |
In Unity, Change which mouse button is used to scroll in ScrollRect I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor). By default it's the left mouse button. I'd like to be able to change this to another mouse button. I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.
|
0 |
Texturing edges of a procedurally generated polygon I'm generating a polygon from code to display unit ranges in my game. Here's how it looks so far I would love to be able to now use my texture and only apply it to the edges of this polygon (imagine a stroke with no fill). Could someone point me in the right direction with this issue?
|
0 |
Can I keep get out of Unity editor features if I'm using ECS Pattern? I'm learning about ECS Pattern to use it in my Unity game, as I saw until now, most of stuffs is created by code. As I know, each Unity GameObject is a Entity which contains many of Components and GameObjects are instantiated by code (created by my script, for example). My question is, when I use ECS Pattern, can I keep using the bunch of features offered by Unity editor (like Prefabs, ScriptObjects, Drag Dropg to position, etc) or I need to control all of them by code?
|
0 |
How to make Sprites scroll with the background image that are inside Scroll View? I'm new in Unity, so I hope you guys can help. I'm developing a 2D game for Android device, on the scene I have a huge background image inside Scroll View (UI Scroll View). Next, I created new empty Game Object "Players", attached to it "Players script" and added "Sprite Renderer" component. From the Sprites I created two prefabs housePrefab and dogPrefab. Inside "Players script" I have the following code SerializeField GameObject housePrefab SerializeField GameObject dogPrefab void Start() var houseXPos 1.41f var houseYPos 2.63f var dogXPos 0.41f var dogYPos 2.63f GameObject house Instantiate(housePrefab, transform.position new Vector2(houseXPos, houseYPos), Quaternion.identity) as GameObject GameObject dog Instantiate(dogPrefab, transform.position new Vector2(dogXPos, dogYPos), Quaternion.identity) as GameObject After I run game both Sprites appears on the screen (as I expected). The problem occurs when I Scroll background image, both sprites stay in the same position under scrolling. In other words sprites not scrolling with the background image. As far as I understand, the Sprites needs to be added to the background image, but I don t know how to do it. How to make Sprites scroll with the background image? Thanks to all in advance.
|
0 |
How can I resize my Blender models when importing to Unity? I made a 3D model in Blender, but when put it in my Unity project and add an FPS camera the camera is bigger then my model. I used the measurements of Blender (that one cube is 1 meter in Unity). How can I fix this?
|
0 |
How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!) I'm currently working on a 2D game where I'm trying to pre populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to quot pop quot in once it is. Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level? Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity) Here is my instantiating code SerializeField public List lt GameObject gt levelEnemies new List lt GameObject gt () GameObject levelEnemy Vector3 enemyPosition Vector3 viewportPosition new Vector3(0.8f, 0.5f, 10f) Place on the screen I decided I want single enemies to appear Camera cam void Start() Debug.Log( quot Enemy Triggered quot ) cam Camera.main enemyPosition cam.ViewportToWorldPoint(viewportPosition) levelEnemy Instantiate(levelEnemies 0 , enemyPosition, Quaternion.identity) instantiate test enemy at the converted position navigation.DisableNavigation() Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3) Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully) Here is what happens when the camera collider bumps into the encounter collider Any help in the right direction would be much appreciated or a workaround! Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)
|
0 |
Combining rotation (using Quaternion Quaternion) doesn't work as expected I have fragment of code that has to rotate the camera to the direction where my cursor is as below float yaw mouseSensitivity.x Input.GetAxis("Mouse X") float pitch mouseSensitivity.y Input.GetAxis("Mouse Y") Vector3 camRotDir new Vector3(pitch, yaw, 0) this works Vector3 camRot mPlayerCamera.transform.rotation.eulerAngles camRotDir mPlayerCamera.transform.rotation Quaternion.Euler(camRot) this doesn't work var rotation Quaternion.Euler(camRotDir) mPlayerCamera.transform.rotation mPlayerCamera.transform.rotation rotation WithmouseSensitivity being an arbitrary Vector2 value representing mouse's sensitivity respectively on axis X and Y. The problem is when I convert the current camera's rotation in Quaternion to Euler angle, add the camRotDir to it and then convert the result back to Quaternion, it works properly, the z component in camera's rotation remains unchanged during this process. But when I first convert the camRotDir to Quaternion and add it to camera's current rotation by multiplying them together, I get unexpected behaviour, the z component was somehow changed. I have no idea why this happens, should Quaterion of (euler a euler b) (Quaternion of euler a) (Quaternion of euler b) ? Code run in Unity 2018.3.12f1.
|
0 |
Nuget in Unity with Mac OS I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac 1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg 2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?
|
0 |
Make one object rotate to face another object in 2D In my 2D project, I have an object that is sometimes above or below another object. Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object. (Here, following Unity's default setup, the z axis is the axis pointing into the screen)
|
0 |
With Unity and Mecanim, how do I trigger an effect animation? We have a Mecanim animation. We'd like to play a particle effect on it at a certain frame in the animation. Do we need to use an AnimationEvent and have it call a function that triggers the effect? Or is there some editor only way to do it without script? We're using Unity 5.3.5.
|
0 |
Use references to UIManager script or direct for children OBJs So I've got a canvas with UIManager script attached to it, the canvas has a lot of buttons and texts as children OBJs and they somehow need to communicate to each other. Should this be done through the UIManager or through direct scripts? EDIT Fixed, the point was to set other buttons and other UI elements active or de active, I ended up using different methods in the UImanager script to do so, without having like 20 scripts.
|
0 |
How can I add intermittent voice chat to a Unity multiplayer game? I'm looking to make a multiplayer horror game with one of the main mechanics being the game's internal voice chat. Currently I plan on making it cut in and out so that the players (being on opposite ends of the map from each other) will lose verbal contact with each other. I planned on using Unity. Do you know how I could go about making this work?
|
0 |
How can I make huge terrains in Unity? How can I make extremely huge terrains in Unity? It seems like I can set width and length to large values. But the Heightmap resolution only goes up to 4097 and the Detail resolution only goes up to 4048. Any ideas?
|
0 |
reuse texture between quad objects This question is specific to unity I want to spawn multiple blocks, each representing a letter. There will be more than one copy of an alphabet. I have a big texture which contains all the letters in it. I use a prefab to Instance all the Blocks(quads) during Awake(). At runtime, I'd like to assign a texture to these quads (identifying the letter). My code looks like this void Update () if there is no active block, spawn it if (activeBlock null) this.getNextBlock (ref this.activeBlock) protected Block getNextBlock(ref Block block) block this.deQueueBlock () char letter LetterMgr.Instance.getNextLetter() based on the letter, index into texture and assign the texture indices to this block ? How can I reuse this one big texture and index into each letter amidst all these blocks (quads) ? I will be rendering this on a mobile, so will need to squeeze all the performance I can. Details 256 x 256 per letter 8 columns x 4 rows Total Texture Size 2048 x 2048 Total number of blocks 100 PS Each of the letters will be moving and will eventually come to rest. So I will have some (around 6 7) actively moving blocks and others will be stationary.
|
0 |
Help understanding IEnumerator Move routine I have this code and I know what it does (it will move an object up and down) But I don't know how its elements work. Could someone please explain it to me? IEnumerator Move (Vector3 Target) What this IEnumerator do? while (Mathf.Abs ((Target transform.localPosition).y) gt 0.1f) Vector3 Direction Target.y Top.y ? Vector3.up Vector3.down Is this an if else? and if yes why if target.y top.y its first choice is vector3.up? transform.localPosition Direction 5 Time.deltaTime yield return null yield return new WaitForSeconds(1f) Vector3 newTarget Target.y Top.y ? Bottom Top Same line but result order is different ?.? StartCoroutine(Move(newTarget))
|
0 |
Buttons only trigger right left movement once, not continually I have a Unity mobile project where I am trying to use right left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right to the left one time, not continually when the player is holding the button down. I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works. Here is my code. (rightCallable and leftCallable are attached to the buttons). using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public GameObject player public float speed 1000f public GameObject left this is so the player may also use the A and D keys if they want, and it works fine. public void Update() var movement Input.GetAxis( quot Horizontal quot ) transform.position new Vector3(movement, 0, 0) Time.deltaTime speed Below is what isn't working public void rightCallable () StartCoroutine( quot moveRight quot ) public void leftCallable () StartCoroutine( quot moveLeft quot ) IEnumerator moveRight() var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null IEnumerator moveLeft () var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null
|
0 |
Animation conversion failed transform for bone not found? I'm trying to animate my first humanoid, and the animations in the Standard Assets pack (HumanoidIdle etc) work really well right out of the box. However, when I try to use other fbx files, like those in Unity's "Raw MoCap Data" pack, I get errors. I import the animations, select one, go to "Edit " and go to "Rig", select "Humanoid", copy the avatar definition from the character I'm trying to animate (e.g. Robot Kyle), and under "Animations" I will get an error like "Imported file RunBackward conversion failed Transform 'Left Thigh Joint 01' for human bone 'LeftUpperLeg' not found". When I compare the avatar of the character I'm trying to animate with the avatar that comes with the animations, they have the same bones defined, just with different names (which shouldn't matter, right?), so it's not that bones are missing. Using the animation with the default avatar also doesn't work, I get no error but my character goes into the first frame of the animation but then freezes. I've tried this with the standard models Ethan and Robot Kyle to the same effect. Does anyone know how to handle this import error?
|
0 |
Problem with Parameters for polymorphism class This is going to be a bit tricky but it is really bothering me so I hope you will have the patience to follow along ) Here is my very basic architecture So in the framework, I am creating I have Actions these currently have a list of Conditions or Considerations (same thing different name). While each Condition share some of the same functionality such as Returning a float score Using an evaluation formula They implement these in very different ways depending on the situation. Take a look at the following code CreateAssetMenu(fileName quot Consider my health vs max health quot , menuName quot AnAppGames AI Example Decisions Health Consideration quot ) public class MyHealth BaseConsideration private float health public float maxHealth public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) health value as float return EvaluateValues(health maxHealth) What you are looking at is my first attempt at making some sort of quot reusable quot Consideration. Now in the continuation of my development, I had to make the following Consideration public class DistanceFromMe BaseConsideration public float minRange public float maxRange private float ConsiderWithValues(Transform target, Transform caller) return EvaluateValues(new FloatData(Vector3.Distance(target.transform.position, caller.position), minRange, maxRange).GetNormalizedData()) public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) Transform target value as Transform if (target null) return 0 return ConsiderWithValues(target.transform, context.transform) public override float Consider(float x) return EvaluateValues(new FloatData(x, minRange, maxRange).GetNormalizedData()) And now the trouble begins I thought quot This is not a scaleable solution quot as soon as I need more than 1 generic parameter I am screwed and have to create additional overrides of this Consider function. So what I need is somehow to add different types of parameters to the Consideration however these parameters will vary a lot. Another problem I have with this is that when I loop through the list I won't be able to tell what parameters i needed and how to fulfill the needs of the Consideration. I thought of different ways of dealing with this inside the editor but I have come up empty ( Can anyone help me out with this architectural mess? ) It is worth mentioning that at the current point each of these are ScriptableObjects I am not 100 set in the fact that they should be but i am just not sure how to deal with this problem.
|
0 |
FSM Transitioning to another state I am using a Finite State Machine for my character who has the ability to change into various forms (Wolf, bird, ect). The character changing to each state is not instantaneous and has a transition period to the next state. Most FSM i've seen set the next state instantaneously. My question is what should I do for the transitioning state? For example the "HumanState" is transitioning to the "WolfState" should I make another state class for each transition (Example HumanState HumanToWolfState WolfState)? Or should I just have the state stay at the current state until the transition is done by using a coroutine and setting the state on completion?
|
0 |
Architecture for extremely modular game? I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in Assets. Each module would be its own project, and I would just drop its build into the launcher's folder. My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo?
|
0 |
How do I define a required component on a Unity game object? I have a script that expected the game object to have a Terrain component. Is there an attribute I can add (or some other way) which will prevent a designer from adding my script component MonoBehavior to a GameObject that does not have the Terrain component? The only alternative I have been able to find is to attach my script to something else, and then have a public Terrain field, which requires the user to attach the terrain object to it. (since the editor won't allow you to associate a different object type.) I just want the reverse. Any thoughts?
|
0 |
Unity Water Cube (to 2D game) I wonder if you can create a cube of water within the unity! I'm starting to use the Unity, and took a sought as to whether there was already something like this ... but have not found any tutorial The idea is to use the 3D feature of water and turn it into a 2D scenario As shown below For this result The idea would be to make the cube of the material is "water". Its possible?
|
0 |
Unity's 'Ambient' Occlusion occludes everything. How to do it better? I'm experimenting with custom AO solutions for Unity. While looking at the source for their built in SSAO effect, I noticed the shader is doing this half ao tex2D ( SSAO, i.uv 1 ).r ao pow (ao, Params.w) c.rgb ao So basically it's darkening the whole image as a post process where the AO term is lt 1, specular and diffuse components included. I'd like my version to only attenuate the ambient component while leaving the direct lighting untouched. So how to go about this? One option would be to go to the full on deferred renderer (not legacy light pre pass), compute the AO texture after the G buffer pass, and incorporate it into a custom shader to do the final lighting pass. But are there simpler options that would work with light pre pass or even forward rendering?
|
0 |
Unity aircraft physics I want to make a simple aircraft controller, what looks like little realistic in unity. I watch some video from airplane physics. and make a simple script in unity, but if I start, my plane cant move or if I change drag to zero, it cant lift. I tried to use real data and get it from wiki(F22 Raptor). To my game object, I gave the rigidbody component mass 19670 kg. Engine thrust 2 116000.0f Newton. private void calculateEnginePower() EnginePower engineThrust ThrottleInput private void calculateForces() angleOfAttack Vector3.Angle(Vector3.forward, rb.velocity) angleOfAttack Mathf.Clamp(angleOfAttack, 0, 90) coefficient Mathf.Pow(1225.04f rb.velocity.magnitude, 2) 1 M 2 2 where M is mach. if (coefficient gt 0.0f) coefficientLift (4 angleOfAttack) Mathf.Sqrt(coefficient) lift 1.2754f 0.5f Mathf.Pow(rb.velocity.magnitude, 2) coefficientLift 78.04f densy1.2754 kg m3, speed m s , (F22)Wing area 840 ft (78.04 m ) coefficientDrag 0.021f rb.drag coefficientDrag 0.5f Mathf.Pow(rb.velocity.magnitude,2) 1.2754f 78.04f rb.AddForce(transform.up lift) rb.AddForce(transform.forward EnginePower) roll, pitch... inputs from keyboard and mouse, EnginePower, RollInput... are simple properties and I call the Move function in a controller inside void Update. Move(float roll, float pitch, float yaw, float throttle) transfer input parameters into properties.s RollInput roll PitchInput pitch YawInput yaw ThrottleInput throttle AirBrakes false calculateEnginePower() calculateForces() calculateRotation() used these formulas for Lift force Lift formula for Lift coefficient Cl formula for Drag Drag formula and for Drag coefficient I used data from wiki too (0.021f).
|
0 |
How to code simple Goomba like AI for 3D Platformer? I'm making a 3D Platformer and have an enemy similar to a Goomba in terms of AI. How do I get the enemy to walk around and then follow the player when they're in range?
|
0 |
How to make camera smooth when following player When my character moves through my cameras 'FollowPlayer' script, the background just looks really glitchy and bad Is there anyway to fix this? This is my script using UnityEngine using System.Collections public class FollowPlayer MonoBehaviour Transform bar void Start() bar GameObject.Find("PlayerMovingBar").transform void Update() transform.position new Vector3( bar.position.x, transform.position.y, transform.position.z)
|
0 |
What game objects can have a "material"? In Unity, I created an empty GameObject called "Person". I created some child objects to it, such as "head" (a sphere), "body" (a capsule), "leg" (a box), etc. Then, I wanted to change the person's color, so I created a material. However, I could not drag amp drop it on the person I could only drag and drop it on each child object separately. My question is what game objects in Unity are allowed to have a "material" on them? And, is there a way I can put a material on a parent object, and let it affect all its child and descendant objects?
|
0 |
Why is this Mono Behavior in the animator? I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to. I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?
|
0 |
Unity Networked gaming 2019... What happened to NetworkBehaviour, OnServerStart() etc After a long break, I am now trying to learn some basics in networked gaming in Unity. I've installed the latest beta client (because I want to ultimately make a network multiplayer game but it will be many months of learning and building barebone prototypes to ensure I can get game objects spawning correctly and be controllable by the correct client etc etc I have some experience in Unet, by extending the NetworkBehaviour class. I don't remember exactly but there were things such as Client RPC and Command and also OnServerStart() methods etc. But I am aware Unet is being removed. And I tried to extend my class from NetworkBehaviour (I also tried NetworkBehavior lol) and it doesn't recognise it anymore. So what replaces OnServerStart() method and ClientRpc instruction? Ideally I want to use a Dedicated Server solution (which I will run on my own computer in order to play small tests online of my game). The game im trying to make to start off with is extremely simple. The 'player' is just a capsule which can shoot small cubes and give damage to other players. Also the player object 'you' are controlling will appear blue, but all the other players will be grey. Using Unet I was able to make the above small game idea work. But now I am unable to.
|
0 |
Seaming between procedurally generated terrain meshes in Unity I have been generating procedural terrain for an upcoming project however I am coming across a seaming effect between the tiles I have searched for solutions including this video. Here is the code (sorry for the lack of comments) chunkx and chunky are the x and y coordinates of the chunk that is being generated. seed is a randomly generated integer. float Gen Height(int x, int y, int seed) float height 0 float newx float newy for (float resolution 128 resolution gt 8 resolution 8) newx (seed 40f) resolution x resolution newy (seed 40f) resolution y resolution height (Mathf.PerlinNoise(newx, newy) 0.5f) resolution if (height lt 0) height 0 return height public List lt Vector3 gt Gen Vertices(int chunkx, int chunky, int seed) float height int x 101 List lt Vector3 gt vertices new List lt Vector3 gt () for (int i 0 i lt x i ) for (int j 0 j lt x j ) height Gen Height(i chunkx (int)x, j chunky (int)x, seed) heightmod vertices.Add(new Vector3(2 i, height,2 j)) if (height gt maxheight) maxheight height else if (height lt minheight) minheight height return vertices
|
0 |
How to hide objects behind an invisible plane? I am using Unity 2019.1.4f1 (personal) in regular 3D mode. I want to make a material for a plane that will cause everything behind that plane to be invisible. I want a character who steps through a doorway to appear to disappear into "hammerspace" when he passes the door frame. I will post pictures in a minute. Blender concept (note how space after the doorframe is successfully occluded) Unity WIP (note how path after doorway is not yet occluded)
|
0 |
3D model editor manipulators I'm trying to make my own 3D model editor to better learn 3D programming. I have my translate manipulators and I'm trying to calculate the Vector2 that the mouse would have to move in order to move an object down a specific axis. This will obviously change based on the position of the camera, position of the object and the axis. I have the majority of it working, I'm just not sure on how to finish it. If the camera is completely horizontal to the object then the values come out correct, but once I start to move the camera above or below the object the values start to get less accurate. I figure I need to incorporate the camera's up vector into it, but I'm not sure how. The code snippet is for the X axis. Vector3 meshCameraDistance meshPosition cameraPosition Vector3 angleAxis new Vector3(1, 0, 0) float meshCameraAngle Vector3.Angle(meshCameraDistance, angleAxis) Vector2 mouseDragDirection new Vector2(Mathf.Sin(Mathf.Deg2Rad meshCameraAngle), Mathf.Cos(Mathf.Deg2Rad meshCameraAngle)) if (meshCameraDistance.z lt 0) mouseDragDirection new Vector3( mouseDragDirection.x, mouseDragDirection.y) speed (manipulatorSpeed.x mouseDragDirection.x) (manipulatorSpeed.y mouseDragDirection.y)
|
0 |
(2D) Take player speed into account while shooting bullets In my top down 2D game, there is a plane as shown below The plane shoots bullets forward. For firing bullets, I use obj.GetComponent lt Rigidbody2D gt ().AddForce(transform.up 500) However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed. How do I take into account player speed so that force applied takes into account player speed?
|
0 |
How to add Facebook Data Storage to Mobile Game? I was wondering how I would add the option for players to sign into their Facebook profiles on my mobile game and then have Facebook store their game save data, so they can recover it on any device when they sign into Facebook. Other Facebook features would include seeing their friends on the Facebook leaderboards, inviting their friends to the game and challenging their friends to beat their scores. I would hate for the Player's data to be lost, so the Facebook data save part is very important. A good reference to this feature is the Hungry Shark mobile game. I wasn't sure how this works. My programming friend and I are creating the game together, but he doesn't know how to do this and I don't know how to program. Once I figure out exactly what has to be done, I would like to hire a programmer who knows how to add this feature. Thank you!
|
0 |
Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.
|
0 |
Efficient way to build a 360 rotation system with clockwise and counterclockwise direction I've been struggle with rotation for sometime now, maybe it isn't that hard for someone who dominates the mathematical side of things regarding rotation and angles but, I need to build a rotation system that rotates the player to either clockwise or counterclockwise direction according to the nearest direction to the target angle. I.E. If my player is rotated to 45 and the direction is changed to 135 , he must rotate 90 clockwise (from 45 to 135 ). If my player is rotated to the same 45 and the direction is changed to 315 , he must rotate 90 counterclockwise (from 45 to 315 ). This didn't seemed a big deal when I started, but it's been hard for me to build something that cover all the rotation possibilities, which tells me that I'm doing something wrong here. I mean, there's must be a couple of formulas that fit this problem and cover all the possible rotations or something. Right now, my rotation system is configured to a minimal of 5 degrees of rotation, wich means that the possible degrees goes from 0 to 355(it never get to 360, going back to 0 instead). I don't have a code to show cause everytime I try to build this, I reach to a point where there are so many possibilities that aren't covered by my tests that I end up deleting everything to try again, but I'm tired of this seemingly endless loop (for me anyway lol). Does anyone knows a way to build this? EDIT My project is 3D and the camera perspective is similar to sports games like NBA 2K or soccer games in general. The input is a Vector2 obtained with the new input system. I need to move my player around with root motion, which means that my goal with this system is to calculate the rotation data to be passed as an animation parameter (using a event), so the correct animation is played and the player finally rotate according to the animation. The main part of the code (calculation part) was built by a friend of mine, who has more knowledge than me. This is my current code if (movementVector ! Vector2.zero) targetRotationAngle Mathf.Atan2(movementVector.x, movementVector.y) Mathf.Rad2Deg cameraTransform.eulerAngles.y FUNCTIONAL CODE BUILT BY A FRIEND targetRotationAngle Mathf.CeilToInt(targetRotationAngle 5) 5 FUNCTIONAL CODE BUILT BY A FRIEND if (targetRotationAngle lt 0) targetRotationAngle 360 if (currentRotationAngle targetRotationAngle) return else if (currentRotationAngle lt targetRotationAngle) Debug.Log( quot Clockwise rotation in quot (targetRotationAngle currentRotationAngle) quot degrees quot ) if (currentRotationAngle gt targetRotationAngle) Debug.Log( quot Counterclockwise rotation in quot ((360 currentRotationAngle) targetRotationAngle) quot degrees quot ) currentRotationAngle targetRotationAngle This is a summarized version of my previous attempts (the ELSE part), I know my formula is wrong, cause it doesn't cover all the rotation scenarios, the more I tried to build, more of this IF's were nesting. That's why I've decided to ask...
|
0 |
Controlling Unity 3D cube with remote gyroscope This probably will go into conceptual things as well, but what I would like to do is take a Raspberry Pi (with a Sense Hat), transmit the gyro values to Unity, and effectively have a 1 1 realistic representation of orientation changes. I have no problem transmitting values from the Pi to Unity (though learning about hidden firewall rules was fun), however I am lacking some understanding of how to transform raw gyro values to something representative in Unity. I have not calibrated the Sense hat recently, but know that is something that should be done. For example, I am transmitting the pitch roll yaw values from the Pi (resting normally, these are about 100.30272132022793, 351.3885231076573 354.9306950697191). I have a cube gameobject that I've flattened out and set to the origin. My question is basically, what is the best way to translate raw values from some anonymous object to the Unity coordinate system, and have it rotate appropriately? I don't necessarily want its position to change, just rotation. Screenshot for reference. Raspberry Pi sending gyro data is on the left, Unity is on the right. Tabletop (flattened cube) is what I'd like to rotate to simulate a ball balancer.
|
0 |
How can I avoid instantiating multiple instances of a RigidBody? I could use a little help. I've a state machine for an NPC that does a melee attack. The problem I'm running into is that the current code instantiates multiple instances when I only need one per cycle. I could use some ideas. This is the chunk of code I'm working with public void ChaseToAttack() navMeshAgent.speed 3.5f slow down the navAgent float playerDistance Vector3.Distance(chaseTarget.position, transform.position) stop navMeshAgent to begin attack sequence if (playerDistance lt stopAtDistance) ensure enemy is always looking at player enemyToTarget ((chaseTarget.position offset) eyes.transform.position) if(Physics.Raycast(eyes.position, enemyToTarget, out hit, sightRange) amp amp hit.collider.CompareTag("Player")) navMeshAgent.Stop() currentState attackState StartCoroutine(FistTimer()) PunchCycle() ensure the enemy isn't hitting air amp will always look for the player else transform.Rotate(chaseTarget.position, searchTurnSpeed Time.deltaTime, 0) end look amp atttack player block void PunchCycle() StartCoroutine(AttackCycle()) void PunchClone() clone Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody clone.transform.Translate(0,1f,0) clone.velocity transform.TransformDirection(0.0f,0.0f,0.125f punchDistance) IEnumerator AttackCycle() move animation here AnimPunch() PunchClone() yield return new WaitForSeconds(4f) fistTimer BeAlert() Thanks in advance... EDIT Changed the code so it would only instantiate once but now, it will only instantiate only once even though it's still in the attack sequence. public void ChaseToAttack() navMeshAgent.speed 3.5f slow down the navAgent float playerDistance Vector3.Distance(chaseTarget.position, transform.position) stop navMeshAgent to begin attack sequence if (playerDistance lt stopAtDistance) ensure enemy is always looking at player enemyToTarget ((chaseTarget.position offset) eyes.transform.position) if(Physics.Raycast(eyes.position, enemyToTarget, out hit, sightRange) amp amp hit.collider.CompareTag("Player")) navMeshAgent.Stop() currentState attackState StartCoroutine(AttackCycle()) ensure the enemy isn't hitting air amp will always look for the player else transform.Rotate(chaseTarget.position, searchTurnSpeed Time.deltaTime, 0) end look amp atttack player block void PunchClone() if(!didClone) clone Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody clone.transform.Translate(0,1f,0) clone.velocity transform.TransformDirection(0.0f,0.0f,0.125f punchDistance) didClone true IEnumerator AttackCycle() move animation here AnimPunch() yield return new WaitForSeconds(0.75f) fistTimer PunchClone()
|
0 |
How can I move my player on exact x and y coordinates, like on a grid? I'd like to implement movement exactly like it is done in this game. (You can see it in action on YouTube.) I need my Player to always stay in the center of X and Y similar to grid movement, but with free movement line like. Only move on x and y lines. And I need smooth changes at intersections. var x Input.getAxis("Horizontal") var y Input.getAxis("Vertical") var deltaPos Vector2.zero if (Mathf.Abs(inputY) gt Mathf.Abs(inputX)) deltaPos.Y speed inputY Time.deltaTime else deltaPos.X speed inputX Time.deltaTime transform.position deltaPos
|
0 |
Unity Quaternion.LookRotation meaning I've gone through Unity's documentation for Quaternion.LookRotation, but I didn't get the full understanding of how it works. What is the meaning of Creates a rotation with the specified forward and upwards directions? And if I have to rotate my object in X axis I have to modify both X and Z axisVector3 lookAt new Vector3(relativePos.x, 0, relativePos.z) transform.rotation Quaternion.LookRotation(lookAt) , why can't I only just modify the X axis directly to rotate?
|
0 |
Best way to implement Finite State Machine for player character in Unity? I'd like to implement the player in my game as an FSM as described in this guide to programming patterns in games. What is the best way to accomplish this? Should I implement each state as a monobehaviour with a state interface that can be enabled disabled when the state transitions? Or would it better to the states as plain classes (with their own Update method) where the main player monobehaviour calls StateName.Update() from its own Update method (.e.g. void Update() currentState.Update() )
|
0 |
Creating an object in javascript with unity (unityscript) So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error. I have a getter function for my level up stats. and inside of my level up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code function level getter() return base level exp float , lvl exp modifier float , current level int function level up() var level object new Object() level object level getter() level object.current level 1 level object.base level exp level object.base level exp level object.lvl exp modifier level setter(level object.base level exp, level object.lvl exp modifier, level object.current level) I guess my first question is, is it even valid to return an object like that in unityscript?(in the level getter() function). If its not valid what do people suggest I do instead. Set a getter function for each var? My second is how do I declare level object so that it can accept the return if it is valid, and so that I can access the members of the object. I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated.
|
0 |
Rigidbody not working properly I have two objects a player and a wall. The player is passing through the long side of the wall but it collided with the short side of the wall. I want the player to collide with whole wall. Here is the code
|
0 |
Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon.
|
0 |
Unity3d Delay between animation cycles trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue https www.youtube.com watch?v JlLJLHvnkgo
|
0 |
How can I access a method via a string in Unity? I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this public string PlayerPrefsName public GameObject Button public string GadgetForSkin private void Start() GadgetChanged PlayerPrefs.GetInt(PlayerPrefsName) if (GadgetChanged 0) Button.SetActive(false) GadgetForSkin quot GadgetForSkin quot GadgetChanged public void GadgetChecker() GadgetForSkin() public void GadgetForSkin1() If it's not possible, how can I achieve something similar?
|
0 |
How can I push a button with VR hands? New programmer here. I am currently trying to create a sample game in Unity (2019.2.11f1) where I push a button using the VR hands of my Oculus Rift (the hands follow my controllers). I can't believe how difficult is to find documentation or tutorials for said task. I've tried to read documentation but I'm at a loss here. I have tried putting sphere colliders on the Hands, and tried to use raycast, with no success. I use the localAvatar with both grabbers as children, and the avatar is itself child of the OVR Player Controller prefab you get when you download the Oculus asset from the store. How can I achieve this?
|
0 |
Irregular Shaped Colliders For Unity Is it possible to create an irregular shaped collider? If so, how? Would I need to create a couple objects and group them up into one Game Object?
|
0 |
Overlap transparent particles without blending? (Unity) I'm trying to create a continuous output of light from an object (like the exhaust of a space ship), and I thought I'd use particles to achieve this. But I'm running into a problem with alpha blending. I'd like to decrease the particle system's alpha over time, but because there's such a high density of particles, they end up evaluating to a solid color for most of the system's duration. This blog post basically shows what I'm trying to achieve https mispy.me unity alpha blending overlap The idea is to use a stencil test to make sure pixels in a sprite particle aren't gone if they're overlapping another sprite particle. Pass Stencil Ref 2 Comp NotEqual Pass Replace Then the author adds an alpha cutoff to make sure transparent pixels on an underlying sprite don't prevent new pixels from being written. half4 frag (v2f i) COLOR half4 color tex2D( MainTex, i.uv) if (color.a lt 0.3) discard return color But this solution requires you to eliminate soft edges, so I'm thinking it wouldn't look good in a particle system. The author also hinted at an alternate solution involving ZTest, but I can't visualize what that would be.
|
0 |
Why do my objects with colliders go through each other, and how do I fix it? I am new to Unity and I am just experimenting with a player controller script (which I got off youtube) and another object which doesn't move. Both my player and the stand alone object have colliders and rigidbodies but when I move the player it goes straight through the other object. My player controller script is using System.Collections using System.Collections.Generic using UnityEngine public class PlayController MonoBehaviour public float speed private Rigidbody2D rb private Vector2 moveVelocity void Start() rb GetComponent lt Rigidbody2D gt () void Update() Vector2 moveInput new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) moveVelocity moveInput.normalized speed private void FixedUpdate() rb.MovePosition(rb.position moveVelocity Time.fixedDeltaTime) Nothing has been changed on the colliders (nothing ticked), and the rigidbody2D has been changed to kinematic.
|
0 |
trying to get an int grid of values from unity tilemap I'm trying to get a 2 dimensional grid of values from a tilemap and found this which seems to do the trick tileMap gameObject.GetComponent lt Tilemap gt () foreach (var position in tileMap.cellBounds.allPositionsWithin) Debug.Log(gameObject.name " " position) TileBase tile tileMap.GetTile(position) if(tile.name ! null) Debug.Log(tile.name) However, something strange happens as it produces two values, when I only have one tile on the tilemap and when I uncomment my .name log above it only works for the second value and errors for the first. Any help of the best way of finding values from tilemaps would be great.
|
0 |
How should I deal with different enemy types? I'm making simple space shooter game for Android in Unity. I want to have different types of enemies (different weapon, stats, movement schemes) and I'm not sure how to do it. I'm quite new to objective programming and I don't really know what classes should I create. I guess I could just make a prefab for every enemy since there won't be many types, but that is not what I'm looking for. I have some ideas First of all I'd write an BaseEnemy class and enemy type subclasses that inherit from it. My first idea is to create those without MonoBehaviour. Then I'd have to make an EnemyScript with MonoBehaviour that I'd add to enemy game object. It'd have a specific subclass object inside, which will set every variable. BaseEnemy would just have undeclared variables and in subclass I'd set particular values. But I'm not sure how to deal with different movement schemes then. I wouldn't be able to put move() function in subclass since it wouldn't have MonoBehaviour, so I'd have to find another way. I might put in EnemyScript every possible scheme and then use correct one depending on some type value, but it doesn't seem like a proper way, does it? The second idea is to just make a MonoBehaviour BaseEnemy class. Then while creating enemy game object I'd just add correct subclass script (aaand... I'm not sure how to do it ) Could you tell me which one is a better way? Maybe neither of those?
|
0 |
elements of list are changing their values I'm making an app that's similar to an alarm, the user enters time and days, for days I'm using toggles,and storing the values of toggles states in a list which is stored in a list that contain all the inputs of the type days, then the user could edit any of his inputs, his old input are supposed to be shown there , but the problem is even when I'm storing them, old values are changing when I add new elements,(that's when currentToggle is changing) so when he press edit values aren't the same as he entered them I think it has something to do with nested lists but I can't figure out how, ( assigning hours and minutes is perfectly working and both are normal lists) the confirm method is for when the user confirm his choice, and there's edit button that open a panel ,its values are the same as the user entered them before the index gives the number of the selected group of input, dayholder is the gameobject that contains all the toggles , and that's the part of the code that's related to what I've said Toggle toggles List lt bool gt currentToggle new List lt bool gt () List lt List lt bool gt gt daysAll new List lt List lt bool gt gt () void Start () toggles dayHolder.GetComponentsInChildren lt Toggle gt () public void confirm() checkON() daysAll.Add(currentToggle) public void editBut() GameObject panelC EventSystem.current.currentSelectedGameObject.gameObject.transform.parent.gameObject int index panelC.transform.parent.gameObject.transform.GetSiblingIndex() assignDays(index) void assignDays(int index) for (int i 0 i lt daysAll index .Count i ) if (daysAll index i true) toggles i .isOn true public void checkON() currentToggle.RemoveAll(item gt item ! null) for (int i 0 i lt toggles.Length i ) if (toggles i .isOn) currentToggle.Add(true) else currentToggle.Add(false)
|
0 |
How can I shoot an arrow if I know the shot power and target? I am trying to shoot an arrow at a target with a 100 success rate. Given the initial force applied to the arrow, the gravity, the location of the archer, and the location of the target, how can I do this in Unity? I have read How can I find a projectile 39 s launch angle?, and it contains the equation I am using However, this is only accurate when I am at the maximum distance from the object given its power. (Above the maximum distance means that the arrow cannot reach the target.) The closer I move to the target, the less accurate the arrow shot becomes, as it travels past the target. The angle is increased resulting in the arrow traveling a shorter distance as I'd expect, but it is not increased by enough. The script spawns an arrow (a simple sphere) and launches it towards a target. It fires once per second, but the closer to the target the archer is, the more inaccurate the arrow is. The case of the archer being too far from the arrow is not handled, but that is not my concern right now. using UnityEngine using System.Collections public class Archer MonoBehaviour public GameObject arrow Simple 3D Sphere public GameObject target Simple 3D Cube public float power 25.0f public Vector3 aim private void Start() StartCoroutine(ShootArrows()) private IEnumerator ShootArrows() while (true) yield return new WaitForSeconds(1.0f) Vector3 spawnPosition new Vector3(transform.position.x, transform.position.y, transform.position.z) GameObject arrowInstance Instantiate(arrow, spawnPosition, Quaternion.identity) as GameObject arrowInstance.GetComponent lt Rigidbody gt ().AddForce(Aim() power, ForceMode.VelocityChange) private Vector3 Aim() float xAim target.transform.position.x transform.position.x float yAim Mathf.Rad2Deg Mathf.Atan(((Mathf.Pow(power, 2) Mathf.Sqrt((Mathf.Pow(power, 4) ( Physics.gravity.y) ( Physics.gravity.y Mathf.Pow(HorizontalDistance(), 2) 2 VerticalDistance() Mathf.Pow(power, 2))))) Physics.gravity.y HorizontalDistance())) float zAim target.transform.position.z transform.position.z Vector3 aim new Vector3(xAim, yAim, zAim).normalized return aim private float HorizontalDistance() float xDistance target.transform.position.x transform.position.x float zDistance target.transform.position.z transform.position.z float distance Mathf.Sqrt(Mathf.Pow(xDistance, 2) Mathf.Pow(zDistance, 2)) return distance private float VerticalDistance() return Mathf.Abs(target.transform.position.y transform.position.y) My best guess is that I am using the equation correctly, but I am plugging the angle into Unity wrong. Why is my script giving me inaccurate results?
|
0 |
Why is Camera turning with different speed than Player with same code in different scripts? (with unity) I want to integrate a running character in my game, so I downloaded an animation via Mixamo. The player is running and if I attach the camera directly to the Player, it's shaking the camera and the game is not playable. Therefor I made a different script for the camera. In there, the camera is always following the player but turns (like the player) via float h PlayerMovement.horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) (for the camera) and float h horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) for the player. (horizontalSpeed is a constant) But after a few seconds I'm running in a completely different way then I look. Why is that and how can I solve this? I tried different animations nothing worked. Update If there is no rigidbody and no collider attached to it it works fine. But I need them.
|
0 |
Why doesn't anything run after the yield return new line I am trying to make a fade to another scene in unity when I came across a problem. For some reason when the coroutine begins the Ienumerator it only runs half of the Ienumerator Method which is only the anim.SetForBlue line. Heres my code. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class Loseforcube1 MonoBehaviour public GameObject blueWinPanel public Animator animForBlue Use this for initialization void Start() blueWinPanel GameObject.Find("Blue win panel") animForBlue blueWinPanel.GetComponent lt Animator gt () public IEnumerator WaitTillNextScene() animForBlue.SetTrigger("FadeBlueWin") yield return new WaitForSeconds(3.9f) SceneManager.LoadScene(2) void OnTriggerExit() if (GameObject.Find("Cube Player 2")) StartCoroutine(WaitTillNextScene())
|
0 |
Maintain UI position with Aspect Ratio Fitter and anchor preset is set to stretch So i have a text UI using Aspect Ratio Fitter with Aspect Mode Height Control Width and i set anchor preset to stretch upward . To make it easier to understand , i want my text to stretch upward only when screen height is increased , and at the same time , using Aspect Ratio Fitter , i want my text to keep width and height aspect ratio by stretching width when height is increased . And don't worry about screen height size become bigger than screen width size because i have separate UI for portrait . When i apply both anchor preset stretch upward and Aspect Ratio Fitter , UI cannot maintain it position anymore if screen height is increased . So my question here is straightforward , how do i keep my UI inside my camera view while using Aspect Ratio Fitter and anchor preset is set to stretch ? , if possible , can it be done using unity built in feature ? (without me writing the script) Here are screenshot below to show my problem (ps ignore the error it doesn't have any correlation with this problem) Before screen height change After screen height change
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.