_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Ways to move a character in Unity I am studying Unity, and so far I encountered three different ways to move a character. As far as I understand Directly changing the transform ignores both physics and colliders Using a CharacterController component ignores physics but considers colliders Using a RigidBody component considers both physics and colliders. Are these descriptions correct? Which one should I use?
|
0 |
Should a wall be created as a plane or as a box? What are the benefits of a wall being as a plane or as a box? Should I use a plane with a box collider instead of mesh collider?
|
0 |
Should I avoid using object inheritance as possible to develop a game? I prefer OOP features when developing games with Unity. I usually create a base class (mostly abstracted) and use object inheritance to share the same functionality to the various other objects. However, I recently heard from someone that using inheritance must be avoided, and we should use interfaces instead. So I asked why, and he said that "Object inheritance is important of course, but if there are lots of extended objects, relationship between classes are deep coupled. I'm using an abstract base class, something like WeaponBase and creating specific weapon classes like Shotgun, AssaultRifle, Machinegun something like that. There are so many advantages, and one pattern I really enjoy is polymorphism. I can treat the object created by subclasses as though they were the base class, so that the logic can be drastically reduced and made more reusable. If I need to access the fields or methods of the sub class, I cast back to the sub class. I don't want to define same fields, commonly used in different classes, like AudioSource Rigidbody Animator and lots of member fields I defined like fireRate, damage, range, spread and so on. Also in some cases, some of methods could be overwritten. So I'm using virtual methods in that case, so that basically I can invoke that method using the method from parent class, but if the logic should be different in child, I have manually overridden them. So, should all these thing be abandoned as bad practices? Should I use interfaces instead?
|
0 |
Camera Movement Smoothing I am trying to smooth a camera I create in my game, but I can't seem to find a way to actually do this correctly. What I have Calculate the "current" Forward vector var cameraForward Vector3.Cross( Self.forward, target.up) .normalized.Cross(target.up).normalized Rotate the camera on the Y axis of the current target, and X Axis based on delta.y and CurrentVerticalLook cameraForward Quaternion.AngleAxis(delta.y, ViewTarget.transform.up) Quaternion.AngleAxis(CurrentVerticalLook, Self.right) cameraForward var offset cameraForward CameraDistance var pos LookAt offset Self.Position pos Self.transform.LookAt(ViewTarget.position) So what I ahve tried I tried Lerping the Vector Position, I tried smoothing the delta.y based on the last N frames. The Camera I need is something like this Rotate on the Around UP Axis of the target and Rotate on Right Axis of the Camera, Camera Up is always to Target UP. So this is sort of Orbital Camera, but I am having trouble finding the correct rotation operations. The way its set right works, but the camera movement is jaggy, but I can't seem to find a way to add Slerp in there without messing everything. Thanks! Edit lt
|
0 |
Rigidbody2D without pushing eachother on collision TLDR How to stop movement if two Rigidbodies collides? Also, here's a potato video of the problem https gfycat.com ComposedArcticBetafish Say I have three objects in a scene Player Enemy Rock The player and enemies is moving freely, but the rock is static. So I attached a Rigidbody2D on player and enemy to move them around with script. All of them has a Box Collider 2D. Now, if I (Player) move into an Enemy, I will start to push it (changing its position). I don't want this. I can set the Enemy's mass to something large, but then two enemies can still push eachother. I don't want this. If I try kinematic solutions I've found, but then they can move through the rock. I want Player can not move enemies Enemies can not move players Enemies can not move each other Nothing can move or go through the rock Enemies can not move through player Player can not move through enemies I keep reading that if I'm moving colliders, I should also use Rigidbodies for performance. But I can't see how I get this to work with Rigidbodies. How do I set it up? Or should I move away from rigidbodies and set it up myself?
|
0 |
IOS Keyboard as Gamepad in unity So I ve been messing around in unity lately, and I got a vr headset to mess around as as well(google cardboard). I also want to make my own controller to use with this. To achieve this, I want to use a HID complient chip with a arduino. Basicly, this sends usb keyboard input. I was wondering, will Input.getkey(keycode.whateverkey) work with this? I m not sure if that will even register on ios, because iOS keyboard is usually separate from the app because it covers the screen.
|
0 |
How to put trees on procedural generated world created using Perlin noise I have been new to game programming but I knew little bit about Perlin noise. So I have created a infinite world using Perlin noise but I don't be able to understand how I put trees in my world like it is put in game Factorio. My game is a 2d top down.
|
0 |
Have a particle system's particles obey transparency sort mode individually Background In a top down game, I have particles that spawn animated textures. I have my 2D renderer settings set up so that it orders sprites based on their position on th Y axis via "Transparency Sort Mode Custom Axis Y". The Problem But instead of sorting for each particle spawned, what happens is the particle system obeys the setting as a whole so that the sort order is only based on the particle's system's center. Is there a way to have each particle obey Transparency Sort Mode individually? What I want for each particle What actually happens Other Solutions Other people seem to have an old workaround to use GetParticles and setting their "order in layer" individually. See this thread from 2015 https forum.unity.com threads particle systems with sprites order in layer.464533 But I'm trying to find if there's a cleaner solution for Unity 2019 without having to fudge with "order in layer".
|
0 |
Unity Logic for saving and loading objects with both static and dynamic data I need help to get some structure for my save and load. I am making a city builder, so I have Buildings thats need to be saved. Each building has a lot of static Data, for example name, description, etc. However it also has a lot of dynamic Data, for example worldPosition, id, etc. My current structure looks like this On each Building GameObject I keep a reference to a ScriptableObject that stores all the static data. I also store a reference to an Object that stores all the dynamic data. This means I need 2 classes for storing Building data, which I already don't like (BuildingStaticData amp BuildingDynamicData) When I Save Load my game I only need to store the Dynamic data, so for saving I just save the DynamicData. For Loading I load the DynamicData, and instantiate a Building GameObject that is associated with it, then the GameObject has the reference to the StaticData. While this works, I would prefer to have a structure where I only have a single class for BuildingData, but I also don't want to lose the power of a ScriptableObject where I can reference other Prefabs etc. I need some help with this logic.
|
0 |
Unity InputSystem using Unity Events not maintaining values I am testing out using the new Input System and cannot get the values from context.ReadValue lt Vector2 gt () to pass into a private variable. The simple setup is below using UnityEngine using UnityEngine.InputSystem public class PlayerController MonoBehaviour Vector2 leftThumbstickValues void Start() leftThumbstickValues Vector2.zero void FixedUpdate() Debug.Log( quot FixedUpdate quot leftThumbstickValues) Always displays quot FixedUpdate (0.0, 0.0) quot public void Move(InputAction.CallbackContext context) leftThumbstickValues context.ReadValue lt Vector2 gt () Debug.Log( quot Move quot leftThumbstickValues) Displays correct values As you can see, in the Move function it correctly pulls the values from the thumbstick, but when it tries to use the values in FixedUpdate it always equals Vector2.zero. It seems like it should just work, but I think I must have overlooked something very simple. Player Input Settings Input Action Move Properties Input Action Left Stick Properties EDIT I decided to remove the Player Input component and subscribe to the events in code controls.Player.Move.performed cntxt gt Move(cntxt) controls.Player.Move.canceled cntxt gt leftThumbstickValues Vector2.zero This now works as expected. I'm not sure I should mark this as the answer though as it doesn't explain why it doesn't work with the original setup, just offers an alternative solution.
|
0 |
How to setup a public github unity repo with paid assets? From what I gathered (like in this thread or here) I am allowed to push my own game code on github and choose a license, as long as I avoid putting assets I do not own. I want to make it public to be able to show it (to potential employers for instance) but I cannot make it open source as I plan to use paid assets (like DoozyUI). I can avoid pushing the asset itself on the repo (with .gitignore for instance). Should I prevent gameobjects created with this package to be pushed as well ? That would make the game unusable, even with the rights to use the package... Once that is settled, Is it ok to push it to github without license ? Specifically, I do not know if objects generated by a paid asset are still considered that asset or not... Edit I asked the question directly to DoozyUI support, which quickly responded You can upload your project, without the Doozy folder. Thus excluding our source code from being shared. Also, unsert a disclaimer letting anyone know that DoozyUI is required to be installed (before getting your files) for the project to work. You can share any GameObject (or prefabs) you create, but they will not work if DoozyUI is not installed due to missing references (scripts). Once Doozy is installed, they will work as expected. Thus anyone who has the system will be able to see use your project.
|
0 |
Is my collision free location script working? I've recently been learning C and I wanted to take one of my 2D tutorials to Unity. I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors. But, because I'm still only just learning C , I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something? Vector3 spawnLocation new Vector3 (Random.Range (minSpawnX, maxSpawnX), Random.Range (minSpawnY, maxSpawnY), Camera.main.transform.position.z) Vector3 spawnPoint Camera.main.ScreenToWorldPoint (spawnLocation) Vector2 lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Vector2 upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) ! null) spawnPoint.x Random.Range(minSpawnX, maxSpawnX) spawnPoint.y Random.Range(minSpawnY, maxSpawnY) lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner)) I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.
|
0 |
Render Occluded pixels to gray color In 3d space, objects can be occluded by another objects. By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play. To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels. This is the sample images for the case. I guess this can be achieved by some sort of shader. How can I make this effects in Unity 3D Engine? Any hints or idea plz.
|
0 |
Is there a way to turn collision detection system off completely in Unity? My world setup is 2D Top Down. All collisions are disabled from the collision matrix. There are no collisions in the scene as I wanted, but as I perceive, Unity is still trying to calculate collisions in the background. So I'm experiencing serious frame rate drops because of Physics2D.Simulate when I have about 2k colliders moving over each other on the scene. I followed the suggestions about colliders and rigidbodies on the API exactly (so I know the stuff about not to move static colliders without rigidbody, that's not the case here), but I somehow can't manage to tell Unity that I don't want her to calculate "possible" collisions. I only want colliders for Raycast2D, OverlapCircle and making movements a bit realistic. Thanks in advance for all suggestions.
|
0 |
MCS character mouth open is this mo cap animation problem? I have MCS Female Character where I can assigned Mocap to my character. I have downloaded mixamo animation and assigned this to the character but the problem is, the character mouth remains open. I am not 3d artist or animation guy, so here are my question. How can I solve mouth open problem in unity? What is the reason that mouth is open? Either mocap data has open the mouth or what else problem?
|
0 |
How to reduce lag when rendering 40,000 sprites in Unity? I am attempting to render 40,000 sprites a grid of 200x200 with each grid node having a sprite renderer. All the way zoomed out I get about 20 frames per second. What would be the best way to optimize this? Eventually I want to have an even larger grid. The grid has to be changeable mdash I need to be able to change the ground floor for that specific grid node.
|
0 |
Regarding Profile Pictures of Facebook Friends Background I am creating a Leaderboard of Facebook friends in unity. Question Can we download and save the images of Facebook Friends on the device of the user for the purpose of reuse? I would like to store the images of the FBFriends on the user's device so that there is no need to download the same pictures everytime the game is restarted. Is it legal to do so? I asked the same question in Facebook Developers forums but I did not get any response. Kindly guide me. How do devs build a leaderboard of Facebook friends normally? Thankyou.
|
0 |
How can I toggle enabled on a specific script within an object in Unity? I have the CarController script inside my car GameObject. I need to set it to disabled at the start so the countdown timer can start the race. I thought I knew how to do it but once again I have failed Any ideas why this doesn't work?? void TogglePlayerEnabled(bool b) playerCar.GetComponent lt CarController gt ().enabled b void ToggleAiCarEnabled(bool b) aiCar.GetComponent lt CarController gt ().enabled b If I use a print line saying "Toggled" or something, that appears in console as expected. But the CarController script seems like it stays active as both me, and the AI car can just drive whilst the countdown is happening still. Here's the full class public class GameManagerControl MonoBehaviour public GameObject playerCar public GameObject aiCar public int sceneChangeZValue private string countdown "" private bool showCountdown true Use this for initialization void Start () Update is called once per frame void Update () TODO This will change the scene when the track ends. if (player.transform.position.z gt sceneChangeZValue) SceneManager.LoadScene("race track lake") if (showCountdown) StartCoroutine(GetReady()) call this function to display countdown IEnumerator GetReady() countdown "3" TogglePlayerEnabled(false) ToggleAiCarEnabled(false) yield return new WaitForSeconds(1.5f) countdown "2" yield return new WaitForSeconds(1.5f) countdown "1" yield return new WaitForSeconds(1.5f) countdown "GO" TogglePlayerEnabled(true) ToggleAiCarEnabled(true) yield return new WaitForSeconds(1.5f) showCountdown false countdown "" GUI void OnGUI() if (showCountdown) GUI.color Color.red GUI.Box(new Rect(Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box(new Rect(Screen.width 2 90, 75, 180, 140), countdown)
|
0 |
Player with Character Controller and children colliders won't collide properly I have a player that consists on a root object with the Character Controller attached and some children with its components. Those have box colliders attached. When moving the player I want to be able to collide with other objects using the box colliders, but it won't, instead it will only collide with the Character Controller. As you can see in the image, the red object didn't stop when the collider crashed with the framed cube, but it did when it did with the Character Controller. There is any way to use the player colliders instead of the Character Controller for collision detection?
|
0 |
How to make a script on a prefab act on a particular scene instance? I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it. Actionables are prefabs, which have an Actionable component, with the same setup (at the moment). Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array). I also have a quot Turn Off quot Button, which calls stopBuilding() when clicked, disabling the preview placement. When stopBuilding() is invoked by the button click, everything works as expected. I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable. Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly. How do I access the scene object Planet from Actionable prefab? Here is my Planet and its stopBuilding method so far public class Planet MonoBehaviour private GameObject actionableModel ... public void stopBuilding() For debugging only Planet planet GameObject.Find( quot Planet quot ).GetComponent lt Planet gt () Debug.Log(planet.actionableModel) Debug.Log(this.actionableModel) And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event. public class Actionable MonoBehaviour public class OnClick UnityEvent lt GameObject gt public OnClick onClick new OnClick() ... void OnMouseDown() onClick.Invoke(gameObject)
|
0 |
How to handle back press in Unity? By back press on Android, I want to close all the open windows first then exit the game, I see everywhere it's suggested to check input key in Update void Update() if (Input.GetKey(KeyCode.Escape)) if (AreAllWindowsClosed()) Input.backButtonLeavesApp true But my issue with this is that it's calling the code in every frame and also may handle a single press multiple times! Isn't there a single BackPressed event in Unity for this simple task?
|
0 |
How can I make billiard without using Rigidbody? Unity's physics engine isn't deterministic (ie. the results aren't always the same on all computers) so I haven't Idea that how billiard games Implemented.Is there a way to Implementing fake and deterministic physic in unity? I mean I want to make billiard without using Rigidbody http www.bezzmedia.com swfspot tutorials flash8 8 Ball Pool I found this open source project that didn't use physic! this is what I need but unfortunately it's full c and I haven't enough time to convert it to c http downloads.sourceforge.net foobillard foobillard 3.0 win32 2 bin.zip
|
0 |
Velocity and drag in unity So I have an object that is bouncing around the screen randomly, physics still works on it so it will speed up or slow down depending on what it hit and when. To try to normalize the speed I want to apply force or drag when ever it goes above or below the thresh hold. My question is, do I need to make note of the direction the object is moving to add force? Or can I just add force to the way it is currently traveling?
|
0 |
Collision and changing the scene. C I'm running into a problem where I want to create some code that such that if an object (Cube) is destroyed, it to changes to another scene. Here is my code public class Move MonoBehaviour void playerWalk() var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) void OnCollisionEnter(Collision col) if (col.gameObject.name "Cube") Destroy(col.gameObject) void Update () playerWalk() if (Input.GetKeyDown(KeyCode.B)) print("hello") What do do I need to do?
|
0 |
Difference in light between Unity 5.5.2f1 and Unity 2019 The lighting is different between Unity 5.5.2f1 and Unity 2019. Please see the attached image. I dislike the way the lighting is done in the 2019 version. Both verions are installed out of the box, without any additions. What do I need to change set up inside Unity 2019, in order to have the exact lighting as in 5.5.2f1 version?
|
0 |
Masking cameras for Voronoi splitscreen I would like to mask a camera to only render to a certain (non square) region of the screen, to be used as an overlay, for splitscreen, or any other application. The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well. What I'm considering so far Stencil shader on a mesh in front of the camera but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing? Transparent mesh with a cutout I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render I'm using Unity 2019 LTS and the built in render pipeline I feel like there must be a simple answer I'm missing but maybe I'm wrong?
|
0 |
Why is there such a difference in between my scene and game? Here I have 2 screenshots of my problem By the way my water shader works with Screen position and Scene Depth. I can include them here if needed. Here is my shader(GoogleDrive) Added Now it looks like that when I move window quot game quot to the side Added Here's graph's screenshoots P.S. I think it's something in unity's settings but not in shaders(not sure).
|
0 |
How to create a correct Unity package copy, which will not be replaced when you import? I create a "Package 1" consisting of section A (unique) section B (which will be repeated in all my other packages). This package works correctly is he is alone. Next, I create a "Package 2" consisting of section C (unique) Section B (from Package 1). To save time, I replaced the texture maps in the materials belong to old section A parts and replace this part on section C (directly on models in the Mesh.) I renamed most objects in the scene and in the package as a whole. I delete all prefabs of section A and create prefabs section C , because they are not pick up name changes. The prefabs of section B , I left as is. Now when I import Package 2 in the scene that already contains the Package 1 , it begins the mess Package 1 Files are replaced by Package 2 , even them are named differently. How to avoid it? I can t create each scene from scratch, unfortunately it will lead to the insane time consuming. Huge thanks for your support!
|
0 |
How can I create a copy of an object in Unity? I'm new to unity. How can I make some copies of my GameObject in Unity by scripting? I have tried this by the way public GameObject stone 3 void Start () for (int i 0 i lt 10 i ) Instantiate(stone 3, new Vector3(i 2.0f, 0, 0), Quaternion.identity) I can't really understand why it's not working.
|
0 |
Customising character appearance though textures At the moment I am contemplating adding character customisation to my game, however I am unsure what approaches are available when it comes to using textures decals to add facial features (like facial hair, hairstyle, scars blemishes etc). The character in question is stylised with a cel shader like effect. So what are some approaches to take? Should I be using shaders to blend textures together by having the normal diffuse texture and then a mask texture to add facial hair or are there better more efficient results to achieve what I want? Would another possibility be to use a shader and then bake the resultant blended texture to a new diffuse texture and use that? To clarify, the customisation will be through textures only and not through adding changing meshes
|
0 |
Does destroying object at List element make it null? I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help. For reference, here is the code that I came up with based on my current assumptions about lists public List lt BasePickUp gt pickUpQueue new List lt BasePickUp gt () public bool pickUpActive false void Update () if (pickUpQueue 0 ! null amp amp !pickUpActive) pickUpActive true pickUpQueue 0 .ActivatePickUp() Edit I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue ! null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count ! 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!
|
0 |
Why does my disable z depth test shader do not work? I wrote the following shader which purpose is to force draw a mesh over the rest, regardless z depth Shader "Custom AlwaysOnTop" SubShader Tags "Queue" "Overlay" "RenderType" "Overlay" ZTest Always CGPROGRAM pragma surface surf Lambert struct Input float4 color COLOR void surf (Input IN, inout SurfaceOutput o) o.Albedo 1 ENDCG Fallback "Diffuse" It works great, however transparent objects still get draw over it. Setting the queue as Overlay should have solved the problem. White AlwaysOnTop shader Green Transparent diffuse Blue Diffuse The left face of the white cube should be white, no tinted in green.
|
0 |
Problem with the Layer System Tilemap Layer from Unity This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem. My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall. Side Information The Wall Tile is one piece, which covers two tiles. Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything. There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer. What I see as answers Split the wall tile into two tiles and let the wall part be on another layer, then the roof part. Split the character into two parts and do the same thing. Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start. What I tried Trying around with layers and order in layers. Trying around with the tile atlas (adding the sprite, removing tiles)
|
0 |
How does the Unity coordinate system map to screen pixels? If I have a GameObject, say at x 0, y 0, and I want to move it for a 40 pixel to x how can I make that? In don't understand which is the unit of measurement in Unity. If I make something like this where mov is 40 the sprite goes out of screen! void Start() transform.Translate(new Vector3(mov, 0, 0)) it seems like the correct values must be very low, say 0.6, 1, 3, etc. But why?
|
0 |
is there a way to alternate between two state machines? I'm programming an enemy on Unity that has two state machines, one controlling the quot normal quot behaviour of the enemy (that consists in three states idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states attack, dodge and run away). I'm doing these state machines by using enums, like the following code public enum StateMachines NORMAL, BATTLE public enum NormalStates IDLE, PATROL, CHASE public enum BattleStates ATTACK, DODGE, RUNAWAY I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you!
|
0 |
Is it efficient to use colliders on UI canvas in Unity? Basically I have a task where the player will be able to drag an object (as UI Image), and place it inside a bag (another UI image). What's the best optimized way to do so? As I researched, I do not think that using colliders for images is the "best" way to do it. Additionally, I was thinking about checking if the position of the image while dragging overlaps an element however, I do think that would be performant as that would require checking the position on each frame instead of "OnTriggerEnter". What would be the best way to implement such function? Thanks amp Regards, HurpaDerpa
|
0 |
Whats the best way to light up a scene in unity? What I want is a darkish scene with like neon style lights Currently is use the bloom post processing effect but sometimes it doesn't render well on my main camera and looks not as good as it does in the scene My game view with main camera My aim is to get the lighting similar to look like Brackeys party killer game How may I achieve this
|
0 |
Creating dependent values in the Unity inspector I want to create a few values which will be dependent on each other. Specifically, I want total sum of few values always be 100 In unity inspector no matter how I tweak them. E.G. int total 100 int one 20 int two 30 int three 45 int four 5 How can I make other values adjust automatically if I tweak one of them in Unity Inspector?
|
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 |
Can I use two Collision Boxes on the same GameObject? I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children. For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach. When there is a collision, how can I check which Collision Box is hit?
|
0 |
Why should I use getcomponent? I have already referred the animator by using the statement, Animator anim But,What is the use of getcomponent in awake() function.What happens without it.
|
0 |
Is it efficient to have a only data MonoBehaviours on lots of game objects? I'm working on a voxel based game and this solution would make the implementation of networking and other features a lot more easier, it is less error prone, easier to edit in the Editor, etc. So the question is How bad is it performance wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods? (So they only have primitive data stored in them)
|
0 |
Unity 2D graphical glitch cuts sprite diagonally While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why. The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background). Any help would be greatly appreciated. Thanks
|
0 |
Unity Multiplayer functionalities or Google's plug in? I want to add multiplayer matches to a game I'm making for Android PC, and something echoed in my mind would the network functionalities Unity provides work in Android? I ask this because Google has a free plug in for their services, but Unity also offers possibilities. Also, using any of the above, do I need to pay to rent a server? Or, for example, since we need a paid developer account to register our game at Google Play Store, the servers are part of the deal?
|
0 |
How can I create a stretchy, breakable pizza cheese material? I want to create realistic pizza and allow user interact with it. What I want What I created I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle". How can I make the cheese stretch and break when the user moves a piece?
|
0 |
Unity Checkpoint System that remembers NPC interactions Environment changes? I have already implemented a checkpoint system that respawns the player at the last checkpoint they cross through. Now imagine this NPC A interacts with NPC B NPC B walks over to a nearby car A bird flies over the car and takes a dump Player dies tragically (lol) Player respawns at the last checkpoint X Given that checkpoint X is achieved after watching all these NPC interactions, how can I fast forward skip these interactions when respawning the player? The build I have right now respawned at the correct location but of course, the NPC interactions happen again even though they were supposed to end before reaching that last checkpoint (if that makes any sense ) I understand that this can be achieved by saving all the last known locations of the NPCs, flags that indicate whether the bird took a dump (true false). For example, this seems quite tedious for a game like Uncharted GTA where a lot of interactions happen at the same time. My initial thought was to somehow fast forward the entire game to a point where all these interactions are done and dusted. That way, I can safely respawn the player knowing that they don t see something they ve already seen. Sorry for the detailed post Any tips on how this can be accomplished?
|
0 |
Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.
|
0 |
Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result
|
0 |
Unity FP Character Can't Look Vertically I have a FP Character and well, it can't look vertically. Its happened about 3 times now, each time I just replaced it with the standard assets prefab, first few times it worked fine, but then after a little while, I suddenly couldn't look vertically. I have checked and double check the vertical clamping on the prefab and they haven't been touched. I really need my player to be able to look vertically as soon as possible, could someone show me how to fix this? Thanks in advance!
|
0 |
how to work more efficient with UI elements im working on a mobile android game that has many levels and same UI. for every level i have to assign the object and function of every button in every scene level. is there more effiecient way that there will be no need to assign all functions in every scene? thank you for helping
|
0 |
Unity fails to effectively split spritesheet I'm very new to game development and I find it very difficult to split the spritesheets available at opengameart.org. All of them are kind of jumbled together without any fixed grid. The resource I learned from always used neatly assembled sprite sheets and Unity would have no trouble in automatically splitting them. But almost all are randomly placed and Unity cannot split them. For example And below is the automatic splitting in unity How do you guys get the sprites from such spritesheets in unity? Some guidance would be appreciated. Thank you
|
0 |
Changing color of only one gameobject So i have this script the checks if my mouse cursor is over the block and if it is i want the block to change color using System.Collections using System.Collections.Generic using UnityEngine public class BasicBlockFunction MonoBehaviour public GameObject Block public Color StartingColor public Color HighlightColor Color color Ray ray RaycastHit hit Use this for initialization void Start () Update is called once per frame void Update () MouseOver() void MouseOver() ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) print(hit.collider.name) Block.GetComponent lt Renderer gt ().material.color HighlightColor else Block.GetComponent lt Renderer gt ().material.color StartingColor I want to change the color only for the gameobject i have my mouse on.
|
0 |
Fresh Unity Visual Studio 2017 install error Installed Unity 5.6.3p2 (my projects's current version) on a new machine. When I opened the project in Visual Studio 2017 I got a prompt to update the .NET framework from 3.5 to (I think) 4.2.x. I confirmed the upgrade for all projects in the solution but now all I get is this If I close and reopen visual studio I no longer get the upgrade prompt. I tried downloading .NET 3.5 to no avail. Any information is appreciated.
|
0 |
Create sprite renderer using custom material I have done following thing. Create Material Attach sprite with texture type as Texture Add sprite renderer component to game object Assign material to it that I create in last steps There is no sprite available for selection. Following image illustrate my problem correctly. So my question in how to create sprite renderer with custom material?
|
0 |
Why when using Lerp and StartCoroutine to Lerp between 3 and 3 it's not working? private bool alreadyFading false Then private void OnTriggerEnter(Collider other) if (other.tag quot Teleporting Object quot ) if (!alreadyFading) StartCoroutine(Teleport( 3, 3, 5f)) And IEnumerator Teleport(float from, float to, float duration) alreadyFading true var timePassed 0f while (timePassed lt duration) var factor timePassed duration var value Mathf.Lerp(from, to, factor) material.SetFloat( quot DissolveAmount quot , value) yield return null material.SetFloat( quot DissolveAmount quot , to) alreadyFading false Using a break point it's getting to the Teleport function but it's not changing the values from 3 to 3. It does nothing to the shader to the property DissolveAmount. I want it to change the value from 3 to 3 with duration once not ping pong. but it's not just it's just don't do anything.
|
0 |
Folding selected Parent Game Object in the hierarchy I am folding selected parent gameObject with this editor script. It all works well but it also folds other expanded gameObjects which should not happen. For example under two different parents, if I collapse one parent gameObject, even the other parent gameObject gets collapsed. How do I not let this happen? The problem is at rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ()) It takes the root gameObject in a scene but not the selected gameObject in the hierarchy. Here's the rest of the code using System.Collections.Generic using System.IO using UnityEditor using UnityEngine using UnityEngine.SceneManagement public static class CollapseTools private static int wait 0 private static int undoIndex public static void CollapseGameObjects () EditorApplication.update CollapseGameObjects CollapseGameObjects (new MenuCommand (null)) MenuItem ( quot GameObject Collapse GameObjects quot , priority 40) private static void CollapseGameObjects (MenuCommand command) This happens when this button is clicked via hierarchy's right click context menu and is called once for each object in the selection. We don't want that, we want the function to be called only once if (command.context) EditorApplication.update CollapseGameObjects EditorApplication.update CollapseGameObjects return List lt GameObject gt rootGameObjects new List lt GameObject gt () if UNITY 2018 3 OR NEWER Check if a prefab stage is currently open var prefabStage UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage () if (prefabStage ! null amp amp prefabStage.stageHandle.IsValid ()) rootGameObjects.Add (prefabStage.prefabContentsRoot) else endif int sceneCount SceneManager.sceneCount for (int i 0 i lt sceneCount i ) rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ()) if (rootGameObjects.Count gt 0) Undo.IncrementCurrentGroup () Selection.objects Selection.objects undoIndex Undo.GetCurrentGroup () Selection.objects rootGameObjects.ToArray () EditorApplication.update CollapseHelper EditorApplication.update CollapseHelper private static void CollapseHelper () if (wait lt 1) Increase the number if script doesn't always work wait else EditorApplication.update CollapseHelper wait 0 EditorWindow focusedWindow EditorWindow.focusedWindow if (focusedWindow ! null) focusedWindow.SendEvent (new Event keyCode KeyCode.LeftArrow, type EventType.KeyDown, alt true ) Undo.RevertAllDownToGroup (undoIndex)
|
0 |
Unity moving an object around a radius I'm trying to move a 2D object around the mouse position, However, i want to constrain the object from rotating unnaturally around itself, i want it to basically rotate around a radius, similar to how a boat moves. I've provided the boat example below of what i am trying to achieve, the game is called battleboats.io and their rotation around the mouse will not skid, it looks natural like propellers pushing from behind. Here's my code for achieving this in unity public Camera camera public Rigidbody2D rigidbody private float rotationSpeed 200f private float acceleration 4.4f Vector3 GetMousePosition(Camera c) return c.ScreenToWorldPoint(Input.mousePosition) void Update() Vector3 direction GetMousePosition(camera) transform.position direction.Normalize() float rotationAngle Vector3.Cross(direction, transform.up).z rotation rigidbody.angularVelocity rotationAngle rotationSpeed forward momentum rigidbody.velocity transform.up acceleration Any help is appreciated. What i currently have and the result of my code is illustrated in the below gif.
|
0 |
Unity Adjusting 2D physics for different mobile resolutions I created a test project to see how different mobile resolutions affects Unity's 2D Physics. They way I handled the resolutions was to contain all the objects (including non UI objects) in a Canvas and use a Canvas Scaler component to adjust for multiple resolutions. Although this approach is probably not one of the ways the Canvas was not meant to be used, it works well when working with a single orientation. Despite the quick solution to handle the multiple resolutions, there seems to be the issue of the physics acting differently depending on what aspect ratio is being used. Images can be viewed here http imgur.com a p5wmf The green and blue blocks both have the Rigidbody2D and Box Collider 2D components. The floor (big white block) only has a Box Collider 2D component. As you can see from the images above, the different aspect ratios cause the blocks to collide with the floor at different times. Also, when using rigidbody.addforce in the Y direction, the different aspect ratios cause the blocks to jump at different heights. Obviously these issues could cause an unfair advantage in a game with support for several resolutions. So how would I go about adjusting the physics so that the blocks fall and jump at the same rates relative to the different resolutions? Also if there is a more practical way to adjust for multiple resolutions that doesn't involve a plugin and doesn't break physics, let me know!
|
0 |
How can i change the Camera component height in FirstPersonCharacter? The player looks very short. I changed his scale to 2,2,2 but the camera is in the middle it's like the player head is in the middle and not near the top. In the screenshot in the Hierarchy i have a FPSController and the FirstPersonCharacter with the Camera is child of it. The FPSController scale set to 2,2,2 like the two soldiers. But you can see when i'm getting closer to the soldiers it looks like i'm looking at them from the ground. I need to move the camera only up somehow. And this is the camera and the firstpersoncontroller before running the game
|
0 |
How do I calculate sprites frame usage on my platform's ram? I plan on building a 2d game for mobile and possibly pc. I also plan on using sprites frames for the animation of my 2d game. What's stopping me from doing so is because I can't figure out if the sprites frames containing the animation is gonna use up a lot of RAM on my device. Does anybody here know what I'm talking about?
|
0 |
RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.
|
0 |
Sorting layer issue with multiple sprites and a Tilemap in Unity I have a particle system that draws a blood splat. I have a Tilemap that represents terrain. However, the blood splats, which are on a sorting layer in front of the terrain, are somehow rendered both in front of and behind the terrain. I have encountered similar problems before where the particles had some different Z value than the terrain, but that is not the case this time (3D view) Here are the Inspector panels for these objects. First terrain The renderer for the upper (in Y) blood particle system And for the lower (in Y) system And finally my sorting layers, where Base is behind Foreground What might cause this behavior and how can I fix it? Edit Here is the entire BloodSplat prefab
|
0 |
How can I set up a 2D circular boundary in Unity? I wanted to create a virtual analogue stick on Unity. I figured a very simple, 2 part method setting up a tether to the middle of a doughnut container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve. I initially tried to create a 2D circle collider around the doughnut container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut container). Thus was done with multiple if statements if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f However, when testing the code out, the cursor still exceeded the boundaries given Minimum reproducible code for the cursor public class menuScript MonoBehaviour public float speed public Vector2 originPoint private Vector2 currentPoint Start is called before the first frame update void Start() Vector2 originPoint transform.position Update is called once per frame void Update() currentPoint transform.position float step 50 Time.deltaTime float vertical Input.GetAxis( quot Vertical quot ) Time.deltaTime speed float horizontal Input.GetAxis( quot Horizontal quot ) Time.deltaTime speed if (horizontal ! 0 vertical ! 0) transform.Translate(horizontal, vertical, 0) if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f else transform.position Vector2.MoveTowards(transform.position, originPoint, step)
|
0 |
Unity world asset streaming TL DR What approach should i use for streaming a maps assets? My Unity project so far saves terrain meta data (in a flat file for now) and then streams the map as the player moves. Upon completing this, it was clear that if I wanted to stream anything, its information would need to be stored somewhere. With all this said, do I store my entire map's information in a local db or something? For example, where object X must be, where objects C must be, etc etc. Instantiate everything at run time when that particular tile gets streamed. This seems like a solution an inexperienced game dev (me) would come up with.
|
0 |
Get a Vector2 Based on Object Rotation in Unity I feel like there is an obvious answer to this but I can't find it. Is there a function in unity that gives you a Vector2 (or 3) based on the rotation of an object. for example z rotation 0 gt (0, 1) z rotation 90 gt (1,0) z rotation 180 gt (0,1) z rotation 270 gt ( 1,0) I could just write this in my script the long way, but I feel like there might be a function for it in unity
|
0 |
Bullet is not instantiating properly in Unity So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen? Vector3 velocity bullet.transform.forward 1000 GameObject bulletGameObject Instantiate(bullet, shootPoint.transform.position, Quaternion.identity) Rigidbody bulletBody bullet.GetComponent lt Rigidbody gt () bulletBody.velocity velocity Destroy(bulletGameObject, 4f)
|
0 |
Unity blur only selected layers I'm messing around with Unity 2017's post processing tools while making a 2D game that benefits from the parallaxing effect using a perspective camera. Please note that the game is mostly made using sprites. Now, I have a playerGround, a backGround and a foreGround. I wish to blur the background and foreground only but not the playerground. I'd like to know how to do this as playing with the focal length didn't do anything, everything receives the same blur amount regardless of the distance from camera.
|
0 |
Unity gizmos vs. referenced game objects I'm designing a Unity script that I intend to be highly reusable and as easy as possible to setup within the editor. To this end, a number of properties of this script really need some kind of visual representation on screen. It is an unresolved question to me whether the design of the script should require references to placeholder game objects, OR just Vector3's and float's that have associated gizmos drawn for them. Normally a gizmo would be a natural choice, except that Unity gizmos are not directly manipulable (as far as I can tell). Because of this shortcoming I'm having to consider whether depending on references to placeholder game objects is a more designer friendly approach ultimately, in spite of the extra setup required, and that it might be counter intuitive when the placeholder game objects disappear at run time (which my script would do). Is there a community standard or preference here in this case? Can a Unity experienced game programmer designer speak to which approach they feel is more intuitive or more convenient to setup, when using a 3rd party script? Or is this just splitting hairs as long as I ship an example prefab with my script?
|
0 |
Transparent image changing color to very light when used on light background in Unity I'm trying to use this transparent image (transparent brown, with a transparent white shadow) over this background in Unity UI. But the end result is not similar to what I see in photoshop at all. What I expect and what I have inPhotoshop What I get in Unity How can I fix this?
|
0 |
How can I launch the Unity Editor and open a specific project from C code? I created a very simple console application namespace ConsoleApplication4 class Program static void Main(string args) The project I want to open var arg """ projectPath C Users Administrator Downloads New Unity Project""" Start Unity and open the project Process.Start( "C Program Files Unity Editor Unity.exe", arg) But only the Unity Editor is launched the specified project is not opened. What do I need to modify to launch the project?
|
0 |
Force Reload VS soution Explorer when adding new c Script via Unity3d? When I create C script (Create gt C Script) via Unity3d or delete it from Unity3d Visual Studio shows me the warning window. it's annoying. Is there any way to force "ReloadAll" in solution Explorer without the window?
|
0 |
Make platform's visibility distinct from background I have a 2d infinite runner type game which background is changing its colors constantly. Meanwhile the color of the platforms stays the same. This way the platforms at some point(when their color is the same as the background's) become "invisible" for the player. How can I creatively, shortly and conviniently avoid this problem with unity? P.S. I've tried adding glossy material to it but it didn't work.
|
0 |
Achieve same effect as a FixedJoint2D but also match RigidBody2D forces Trying to make an object that is affected by rigidbody physics in exactly the same way as the object it's linked to. So torque, velocity, and any resultant torque or velocity from a collision. This image demonstrates what I mean I've tried using FixedJoint2D, my objects share velocity but do not share torque, applying torque doesn't do anything to either object, it seems locked. I tried using other joints, such as DistantJoint2D(doesn't match y value, only separation value), TargetJoint2D(immediately negates velocity), RelativeJoint2D(The closest to actually working, but glitches out when torque is applied, it acts on a centre of mass between the two connected objects and the objects sort of spin around each other, sometimes getting closer together or farther apart) I also can't just apply the transform position and rotation to the second object, since these objects will be colliding with moving objects. The objects that they collide with slide into the squares and are pinched away when using this method. So I need to know if there is a way to use the FixedJoint2D or RelativeJoint2D or another method or joint that I do not know of to achieve this same effect. Perhaps applying the collision forces happening to one object to the other but it needs to be immediate and I don't know how to apply the collision from one object to another.
|
0 |
In unity how can I make a checkpoint system I have a 2D platformer and if my player dies, he goes back to the start, but I want there to be checkpoints. My current Respawn script using System.Collections using System.Collections.Generic using UnityEngine public class Respawn MonoBehaviour public GameObject PlayerPrefab public Transform SpawnPoint void OnTriggerEnter2D(Collider2D other) if (other.gameObject.tag quot Trap quot ) PlayerPrefab.transform.position SpawnPoint.transform.position I don't know how to implement checkpoints into this.
|
0 |
How can i properly display 2D Pixel sprite's pixels without distortion while it's moving ? (in unity) Introduction to what i'm trying to do Hi, I'm trying to make a 2D Pixel Platformer Game in Unity. Before that i used godot and for some reasons (not about the engine) i switched to unity. And in Unity there are things need to handle by myself, and they were handled by the engine in godot (i guess), because godot is more suitable and compatible with 2D Pixel games (i guess). So i am not sure why the problem happens The Problem In the scene, my pixel sprite is playing his Idle animation (he's only breathing so you can think of that as head and the body moving 1px up and down repeatedly) While playing that simple animation, if my sprite is big enough on the screen, there is no problem and it looks pixel perfect animation is playing without distortion (or disruption idk what was the right word). But if the character looks smaller on the screen, i mean if i scale the character down or keep the scale same and make camera's angle of view bigger, so character looks smaller (not too small a regular platformer character size), What happens is character's eyes visibly goes thinner and thicker as the character plays his animation (head and the body moving 1px up and down repeatedly). Character's eye is 2 black pixels side by side thats it. While the animation playing it kinda distorts. Height changes. Yes I fixed it somehow but.. I fixed it, but idk how and seems like a temporary fix AND i don't think that is how it's supposed to be fixed because we wrote code, I'm okay with writing code for fixing it but first i want to know what was the problem and how to fix it in editor. aaand it just seems weird to write code for simply having a properly functioning pixel sprite animation. How did i fixed it ? just watched this video and added the same script to the camera i have no idea how it worked and why my animation problem was occuring at the first place. What I'm asking for Pleaaaase somebody explain all that to me, why is that happening what are the possible and proper fixes. i'm researching for days and i thought unity had a "big community a lot of tutorials too easy to learn" TL DR when playing animation pixel sprite character's some pixels distorts version Unity 2019.3.3f1 I imported sprite the right way (Filter mode Point(no filter) Compression none, Pixels per unit 16 (that option seems suspicious maybe the problem is about that pixels and units thingies)) I can provide more information about project or directly send you the whole project if you can't reproduce the error. I'm just too curious and want to learn how to have a proper 2D display setup and finally start the fun part coding mechanics etc. since a code about camera solved the issue the problem might be unity's camera settings because unity has no 2D special camera component while godot has Camera2D and Camera3D seperatly. These are just my guesses please teach me what you know.
|
0 |
Lightmapping runtime combine children Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk .ipa size increases too much.
|
0 |
How to obtain a camera stream from Unity without rendering it to the player's screen? I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen? One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.
|
0 |
Unity C Modifying eulerAngles with slider issues I'm using a slider to rotate an object on the z axis. The slider has a value of 1 360 (Whole Numbers) when the slider is moved, I use that value for the eulerAngles z axis value. (NOTE The object is part of a child parent 'string' of instantiated objects and it should only ever rotate on the local z axis). This method is working for some objects in the 'string', but not others. When it's not working, the object I'm trying to rotate spins wildly on the z axis because the objects z value is not a reflection of the slider value (I tested this in the inspector). I can't figure where these 'random' slider values are coming from. Here is the rotation function I'm using for the sliders On Value Change event public void SliderRotate () Target.transform.eulerAngles new Vector3( Target.transform.eulerAngles.x, Target.transform.eulerAngles.y, mySlider.GetComponent lt Slider gt ().value) BTW If I change the x and y values to zero, the problem goes away. However, the objects then loose their correct orientation to their parent (I need the x and y to stay where they are). Thanks in advance for any insight you can offer into this issue. Windows Unity 5.3.5f1 Here is an image that might help clarify
|
0 |
How could I get composite rigid body into unity I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way? Thanks, nova edit So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.
|
0 |
Creating orientation Quaternion from forward vector Suppose that I have an orientation Quaternion Q, I can compute its forward vector from V Q Vector3.forward easily. Inversely, suppose that I have its forward vector V, how do I compute Q? I know that is not possible, please tell me what's needed beside V, in order to compute Q. Motivation behind the problem I have a forward direction of a game object, I want to find out its up direction and its right direction. I can find out all these 3 directions if I have the orientation Quaternion.
|
0 |
How to select light as sun source I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?
|
0 |
Finding x and z value in the direction of another object In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point. This is what I am doing right now if (!(Vector3.Angle(car.transform.forward, obj.transform.position car.transform.position) lt 40f)) arrow.SetActive(true) temp car.transform.position temp.y car.transform.position.y 2f arrow.transform.position temp temp obj.transform.position temp.y arrow.transform.position.y arrow.transform.LookAt(temp)
|
0 |
How to animate material change to get a status bard effect, in unity Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other. Is there a way to achieve this in Unity? Or do you need to generate the animations in Blender or similar and control them in unity?
|
0 |
How can zoom into my object when that object is being clicked? Suppose that I have the three game(cube,Quard,sphere) object. When I click on a particular game object suppose think I have clicked on the cube,the cube object should get zoomed in on the screen. how can I do that? How do I center and zoom into my cube game object after selecting the cube? I think it has something to do with the camera but how do I center the view with the camera? I have used the below code for zooming the object.For one object its working.But when I place different object and apply this code then when i click on one object all the three object is getting zoomed. Can anyone help me out in solving this issue Here is the code function OnMouseDown() OrthoZoom(1.5) function OrthoZoom(size float) var cam Camera.main while (cam.orthographicSize ! size) cam.orthographicSize Mathf.MoveTowards(cam.orthographicSize, size, speed Time.deltaTime) yield
|
0 |
How do I draw lines to a custom inspector? I have a custom editor to which I want to be able to draw a basic line graph. I have much of the functionality down, but I have only been able to test as much via the debug. I am yet to figure out how to draw the actual lines to the inspector. How do I draw lines to a custom inspector? I have found plenty of online resources, in regards to custom drawing to the editor. However, everything I find pertains specifically to drawing in the scene view nothing seems to work inside of an actual inspector. The two general methods I have found involve using Handles.DrawLine and the GL library. Neither appear to work however, I have only been able to test functionality with blind coordinates, so far. I can not find anything in regards to actually determining the local coordinates of the area on the inspector where I wish to draw. Perhaps I need to start with an initial "origin" position, Perhaps I need to start with a local area defined by a Rect. I simply don't know. It has also been a while since I had to use OpenGL, directly. It is entirely possible I am simply doing it wrong, to begin with. Here is my current graph method private void DrawVelocityGraph(float velocityValues, float minimumVelocity, float maximumVelocity) float velocityValue velocityValues 0 float increment 0 Vector3 lineStart Vector3.zero Vector3 lineEnd new Vector3(horizontalIncrement, velocityValue verticalIncrement) GL.Begin(GL.LINES) for(int i 1 i lt velocityValues.Length i ) if(velocityValue velocityValues i amp amp (velocityValue minimumVelocity velocityValue maximumVelocity)) Handles.color VelocityGrapherColours.outOfRangeColour else velocityValue velocityValues i Handles.color VelocityGrapherColours.lineColour lineStart lineEnd lineEnd.x increment lineEnd.y velocityValue verticalIncrement GL.Vertex(lineStart) GL.Vertex(lineEnd) GL.End()
|
0 |
Optimizing spawning 500 objects every 3 seconds Using Object Pooling, assuming I'll like to spawn 500 cubes once every three seconds. How do I make it performance friendly? I need ideas, not the code itself.
|
0 |
Can I force a manually created texture to not be divided with low quality? I have a texture that I have created that looks something like this . This is a very low texture map, but it helps me in a shader that I'm making that distinguishes between land and ocean, the ocean tiles do different things than the land. To try and figure out what was going on, I used the shader to turn the ocean, as defined by the mask, black. Note that this image doesn't match the ocean texture example from above, but it's the best I had... The ocean is a binary color, either it is ocean or isn't, and is set appropriately. But what I'm actually seeing is that if the 2x2 tile area has mixed land ocean, the value is averaged. What I've noticed is that the pixels were combining together, a 2x2 pixel area was averaged. After tracing through this for some time, I discovered that the issue was a quality setting that reduced the resolution of certain images. There are some images that I don't mind lowering the resolution of, but images such as this one I absolutely don't want to lower the resolution. Is there a setting that I can add to a runtime generated texture to tell it not to reduce it's resolution if requested to by the quality settings? EDIT Code fragments to produce the results above. It's kind of hard to pull just the fragments that produce this code and not produce an overwhelming bit, but hopefully this will do. Code to generate textures Color32 windMask new Color32 world.width world.height for (int x 0 x lt world.width x ) for (int y 0 y lt world.height y ) windMask x world.width y world.Tiles(x, y).baseType Tile.BaseType.Ocean?new Color32(255,255,255,255) new Color32(0,0,0,255) sharedMaterial.SetTexture(" WindMask", TextureUtilities.TextureFromColors(world.width, world.height, windMask, FilterMode.Point)) public static Texture2D TextureFromColors(int width, int height, Color colors, FilterMode filterMode FilterMode.Trilinear) Texture2D texture new Texture2D(width, height) texture.SetPixels(colors) texture.filterMode filterMode texture.Apply() return texture The Shader code o.Albedo 1 tex2D( WindMask, IN.uv MainTex).r The "Fastest" quality settings that show the issue The "Fantastic" quality, which correctly isolates the ocean. Image of the correctly isolated ocean The issue is the "Texture Quality", which you will note for the fastest setting is half resolution. I would really like to keep the ability to use lower resolution in the game, but have a few textures that do not use the lower resolution if the quality settings change.
|
0 |
Loading scene doesn't reactivate gameobjects I have some levels and a main menu. When starting the game from the main menu (in the editor debug mode) I can select a level a load it, no problem. However, when I wish to go back to the main menu using SceneManager.LoadScene(index) A whole lot of my gameobjects throw exceptions like The gameobjects is destroyed, but you are trying to access it and Missing reference exception and so on. However, when i start the level from the editor (and not using the main menu), I can go back to the main menu, it works as it should. NOTE that I don't have any persistent gameobjects. I do have singletons, but no persistence here. Any ideas what could cause the issue?
|
0 |
How to apply fast slow camera transition I know there is a lerp function there that smoothens the camera but I wanted it to work the other way around. Lets say starting position of the player is at the left side of the camera screen and when the players goes around the right edge (or as long as more than half width) screen travelled I want to camera to snap to the player but with smooth transition and this is the hard part I wanted to make the camera move fast as long as it is less than half of the players distance travelled and apply a slow speed as the camera travels more than half the distance of player.
|
0 |
Shader works in Editor but not on iPhone I am using the next script for a painting asset found on this website. As you render the faces of your mesh in the uv space of the mesh, you are reconstruction the islands one triangle at the time. On the edges of the island, it can be that due to underestimation the rasterizer doesn t consider a pixel which is actually in the island. For these pixels, no pixel shader will be executed and you will be left over with a crease. (text and image taken form the website) The basic idea is that every frame, after the paint texture has been updated, I run a shader over the entire texture, and using a filter and a pre baked mask of the uv islands, extend the islands outwards. The problem is that it does not work on iPhone. There is no error, no weird coloring, it is like that script does not get applied. I am not sure where the problem is coming from..maybe the for loops or the command buffers used in c . Shader "Unlit FixIlsandEdges" SubShader TAGS AND SETUP Tags "RenderType" "Opaque" LOD 100 Pass DEFINE AND INCLUDE CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" DECLERANTIONS struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex uniform float4 MainTex TexelSize sampler2D IlsandMap VERTEX FRAGMENT v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) float map tex2D( IlsandMap,i.uv) float3 average col if (map.x lt 0.2) only take an average if it is not in a uv ilsand int n 0 average float3(0., 0., 0.) for (float x 1.5 x lt 1.5 x ) for (float y 1.5 y lt 1.5 y ) float3 c tex2D( MainTex, i.uv MainTex TexelSize.xy float2(x, y)) float m tex2D( IlsandMap, i.uv MainTex TexelSize.xy float2(x, y)) n step(0.1, m) average c step(0.1, m) average n col.xyz average return col ENDCG I've read somewhere that using tex2D in for loops is a big no no, so I changed that to a tex2Dlod but the same thing happens. You can check out the Git project here I am completely lost on this one and google isn't very helpful. Thank you for any comments.
|
0 |
Unity transform.rotation not giving real value i confused , when the object is at 0 rotation ( not rotated yet ) , it giving real value ( 0 ) , but when the object is rotated 180 degree , transform.rotation is giving false value ( 1 ) , this is the screenshot If the picture is not clear enough , go here https i.stack.imgur.com miWIE.png . Then this is my script that debugged the code and rotate the object void RotateFlip() GameObject databasegameobject GameObject.Find ("database") database databasechange databasegameobject.GetComponent lt database gt () Debug.Log ("current object rotation is " theiconarrow.transform.rotation.z " degree ") if (databasechange.pengertianmenustate 2) if (theiconarrow.transform.rotation.z 0 ) theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World) if (databasechange.pengertianmenustate 1) if (theiconarrow.transform.rotation.z 180) theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World) I don't understand why this thing happened , is this a kind of bug or what ? I am sorry if this already asked somewhere , but i just don't know how to find it at search engine ( neither here ) . Extra question ( optional ) is there any application to build app with easy coding and not an game engine ?
|
0 |
Finding out which Panel was clicked in function I have a panel with 10 sub panels in it. I am using Event Trigger to intercept the messages from these sub panels OnPointerDown event calls some function in the some script of an Game Object. Is there a way to know in the function which of the sub panels was clicked. That way I can use the same function for all the sub panels or should I make individual function for each of the sub panels.
|
0 |
Why does collision only work when keys are being pressed? My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1. I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world. So, I would like to know if I'm doing it right or is there another way to do it. Patrol.cs public class Patrol MonoBehaviour public Transform patrolPoints public float speed private int currentPoint private bool forward Use this for initialization void Start () transform.position patrolPoints 0 .position currentPoint 0 forward true Update is called once per frame void Update () if (transform.position patrolPoints currentPoint .position) if (currentPoint lt patrolPoints.Length 1 amp amp forward) currentPoint else currentPoint forward false if (currentPoint 0) forward true transform.position Vector3.MoveTowards (transform.position, patrolPoints currentPoint .position, speed Time.deltaTime)
|
0 |
Unity Change base class variable to a derived class in inspector dynamically In an item system I'm trying to create I'm using prefabs to store an item's default values, and then grab that item from the prefab to use in runtime. It works well, but I was wondering if there was a way to dynamically change a variable with a base type to a derived type, probably with a custom editor, so that I wouldn't have to make separate classes for each derived type. This is the how I'm imagining it would be like public class ItemPrefab Monobehaviour public ItemTypes itemType public Item item public enum ItemTypes meleeWeapon, rangedWeapon Item is an abstract base class, and MeleeWeapon and RangedWeapon are serializable derivatives. With that, I'm trying to do something to the effect of this switch (itemType) case ItemTypes.meleeWeapon item item as MeleeWeapon break case ItemTypes.rangedWeapon item item as RangedWeapon break I was wanting it to be the same as the below, just less scripts. public class MeleeWeaponItemPrefab Monobehaviour public MeleeWeapon item public class RangedWeaponItemPrefab Monobehaviour public RangedWeapon item Edit Here is my item system so far (I just included MeleeWeapon because I didn't want this to get too long). public abstract class Item Header( quot Basic Info quot ) SerializeField private string name quot quot SerializeField private Image icon null SerializeField private GameObject itemPrefab null SerializeField private float weight 0 SerializeField private int maxStack 0 private Guid gUID public string Name gt name public Image Icon gt icon public GameObject ItemPrefab gt itemPrefab public float Weight gt weight public int MaxStack gt maxStack public Guid GUID get return gUID private set gUID Guid.NewGuid() public abstract class Weapon Item public abstract void Attack() System.Serializable public class MeleeWeapon Weapon Header( quot Weapon Attributes quot ) SerializeField private MeleeWeaponTypes weaponType default SerializeField private float damage 0 SerializeField private float chargeDamage 0 SerializeField private float meleeSpeed 0 SerializeField private float chargeTime 0 SerializeField private float chargeCooldown 0 public MeleeWeaponTypes WeaponType gt weaponType public float Damage gt damage public float ChargeDamage gt chargeDamage public float MeleeSpeed gt meleeSpeed public float ChargeTime gt chargeTime public float ChargeCooldown gt chargeCooldown public override void Attack() attack I have other stuff in Weapon and its derivatives but I removed it to keep the base idea more simple. Anyway, I then have prefabs with a MonoBehaviour that hold a derived type of Item, like I showed above, as data containers that I use to instantiate items during runtime.
|
0 |
unable to see sprite in scene Getting error as floating point precision limitation I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation it is recommended to bring the world coordinates of game object within smaller range I am following ruby's adventure tutorial in unity learning
|
0 |
How to develop custom Unity graphics? Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them. p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C . How can you achieve similar graphics capabilities in the Unity Game Engine? Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C . How can you have that kind of creative freedom to build and draw in Unity? Thanks.
|
0 |
How can I scale my UI elements to the lesser screen dimension in Unity 5? I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas) The D Pad, which will be anchored to the bottom left side. The button group will be anchored to the bottom right side. I would like to resize the element on different resolutions, so that the element (in my case, the D Pad is an image) Has a size of 20 of the minimum of the width and the height. Has pivot of x 0.5, y 0.5. Having anchor of left bottom, its coordinates are (15 , 15 ) wrt the minimum of the width and the height. What I tried is to use an Aspect Ratio Filter in the D Pad image with ratio 1, but it did not work as intended (the coordinates led the image to an unexpected place). Note I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size These images should illustrate what I want to achieve What should I do to make it work like in the pictures? Edit I attached this behavior, based on answer, to handle the change by runtime RequireComponent(typeof(UI.CanvasScaler)) class CanvasSmartScaler MonoBehavior private CanvasScaler scaler void Start() scaler GetComponent lt CanvasScaler gt () void Update() OMITTED CODE here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines if (Screen.currentResolution.width lt Screen.currentResolution.height) scaler.matchWidthOrHeight 0 else scaler.matchWidthOrHeight 1 And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1 case regardless how do I resize the window. What am I missing?
|
0 |
How to avoid game starting before start button is clicked? I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start. Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right. This is my first game ever, so hope the code provided is relevant. Enemy.cs void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") GameManager.cs public void StartGame() powerup.transform.rotation) score 0 UpdateScore(0) isGameActive true titleScreen.gameObject.SetActive(false) void Update() enemyCount FindObjectsOfType lt Enemy gt ().Length if (enemyCount 0) roundNumber SpawnEnemyIntruders(roundNumber) Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation) void SpawnEnemyIntruders(int enemiesToSpawn) for (int i 0 i lt enemiesToSpawn i ) int enemyIndex Random.Range(0, enemies.Length) Instantiate(enemies enemyIndex , GenerateSpawnPosition(), enemies enemyIndex .gameObject.transform.rotation) public void GameOver() restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) isGameActive false PlayerController.cs void Start() playerRb GetComponent lt Rigidbody gt () playerAudio GetComponent lt AudioSource gt () StartButton.cs void Start() button GetComponent lt Button gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () button.onClick.AddListener(StartThis)
|
0 |
My money will only save for one game run I am trying to make a money system my problem is that the money value only saves for 1 game run then the value returns to 0. Here is my code. What should I do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Money variables public Text cash Use this for initialization void Start () if (counter lt 9 amp amp counter gt 1) money money 2 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 10 amp amp counter lt 20) money money 5 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 21 amp amp counter lt 30) money money 15 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 31 amp amp counter lt 40) money money 25 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 41 amp amp counter lt 70) money money 50 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 71 amp amp counter lt 100) money money 75 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 101 amp amp counter lt 200) money money 100 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 201) money money 150 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) cash.text "Credits " PlayerPrefs.GetInt("money", money)
|
0 |
Take a screenshot from camera problem I use script below to take a screenshot from camera. It's working fine. However, when I take a screenshot again (pressing k multiple times), its old image is not clear from the memory and it keep drawing over same image over and over again. If object is moving while taking screenshot multiple times, image I will get all frame combine into one image with every frame in the same image. What should I do to fix this problem? using UnityEngine using System.Collections public class HiResScreenShots MonoBehaviour public int resWidth 2550 public int resHeight 3300 private bool takeHiResShot true public static string ScreenShotName(int width, int height) return string.Format(" 0 screenshots screen 1 x 2 3 .png", Application.dataPath, width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) public void TakeHiResShot() takeHiResShot true void LateUpdate() takeHiResShot Input.GetKeyDown("k") if (takeHiResShot) RenderTexture rt new RenderTexture(resWidth, resHeight, 24) camera.targetTexture rt Texture2D screenShot new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false) camera.Render() RenderTexture.active rt screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0) camera.targetTexture null RenderTexture.active null JC added to avoid errors Destroy(rt) byte bytes screenShot.EncodeToPNG() string filename ScreenShotName(resWidth, resHeight) System.IO.File.WriteAllBytes(filename, bytes) Debug.Log(string.Format("Took screenshot to 0 ", filename)) takeHiResShot false Debug.Log("Capture!!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.