#archived-code-advanced
1 messages ยท Page 60 of 1
in case you're curious: a ref field on a class doesn't really make sense
you need to make sure that the ref never becomes invalid, but it's very hard to prove that a heap-allocated object's lifetime is finite...
I have seen this happening on my code when compiling / saving changes , it doesnt happen during play mode, my native arrays are being disposed on destroy, any ideas?
cant quite remember if this happened in the previous version I was using , I think it wasnt so maybe its a bug?
I can see something called native debug compilation, enabling it doesnt show where the leak comes from
wait, where is that dang thing
i wonder if it's actually this guy here
JobTempMemoryLeakValidation
user settings, Diagnostics
it is, but weird think, nothing on console
I even enabled job stack traces and there is nothing
the error magically disapeared
Oh wait it suddenly appeared
I think this is happening because I am using a plain C# class instead of a monobehaviour, the stack trace points me to part of the code that should only happen during play mode
no I meant new person in this discord group
been using Unity for past 3 years
actually I had been searching such find of discord channel
because of my college project, which is multiplayer FPS android shooter
please have a look in this video
so my move joystick is getting stuck at the last position as soon as I am pressing the shoot button
I tried adding them in there own separate canvas's, but this problem is still here.
It sounds more like a problem with handling inputs. Are you handling each touch separately?
no i might not
this is my input managaer script
using UnityEngine;
namespace HOTTEA
{
public class InputManager : MonoBehaviour
{
private static InputManager _instance;
public static InputManager Instance
{
get
{
return _instance;
}
}
private PlayerControls playerControls;
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
playerControls = new PlayerControls();
Cursor.visible = false;
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
public Vector2 GetPlayerMovement()
{
return playerControls.Player.Movement.ReadValue<Vector2>();
}
public Vector2 GetMouseDelta()
{
return playerControls.Player.Look.ReadValue<Vector2>();
}
public bool PlayerJump()
{
return playerControls.Player.Jump.triggered;
}
public bool PlayerExit()
{
return playerControls.Player.Exit.triggered;
}
public bool PlayerShot()
{
return playerControls.Player.Shooting.triggered;
}
}
}
this my player controller script
this is my fpscontroller script
When you press mobile device in several places several touches are registered. Some inputs like Input.mousePosition return the average position of all touches (e.g. the center of your screen will be returned if you press left and right sides of your phone at the same time). When designing an app with a UI like yours it's necessary to check if each input is interpreted properly.
so how do i do that ?
kind new to android game development
any good tutorial for this
Here is a tutorial for using touches in the new input system:
https://www.youtube.com/watch?v=4MOOitENQVg
๐ฅ Download the Source Code ๐ฅ
แ
https://www.patreon.com/posts/75112992
๐ค Support Me ๐ค
Patreon: https://www.patreon.com/samyg
Donate: https://ko-fi.com/samyam
This video gives an overview on how to use Touch from the new Input System through Input action assets and the PlayerInput component, how to simulate touch in the editor game view, an overv...
thank you will check this one out
I do a sphere cast in unity to detect the ground the player is standing on. When the player stands on the edge of a cube, the normal that is returned is not facing up. Instead, it is facing between the normals of the edge's faces. Since I'm using the ground normal to decide whether the player should slide off the surface or not, the player ends up slipping of the edge.
Does anyone know how to get the normal of the face?
In unreal, when you do a cast you get a "normal" and an "impactNormal". One represents the interpolated normal while the other represents the normal of the face at the point of the impact. Maybe there's an equivalent in unity?
Is it something like that it is happening ?
So I've got an abstract class for a WorldObject, which can be stored in a Tile class as an Occupant. However, when I run this function that goes through the list of tiles for if the occupant is null and adds the occupant to a list if its not, its coming up with an error that states "Object reference is not set to an instance of an object". whats going on here?
from what i can tell its saying that a variable, which should have been set to have an instance, is null for some reason
TotalObjects could be null, in which case you're calling Add on null which is an error
exactly - and in this case the variable is TotalObjects
but why would it be null? Its a List variable, its there!
its just saying its not there despite it being there???
and its giving me this same exact error message when other scripts call upon it, its just saying that its not there?
why would it not be there if its a variable that exists? why would it say it doesnt exist?
this gives the same exact error
A List variable is not a list
it's a reference to a potential list
this is what its saying is null
it has to to be assigned to an actual List object
You would have to say TotalObjects = new List<WorldObject>(); somewhere to actually initialzie the list
i see
Again you have a reference variable. It needs to be assigned to an actual object otherwise it's null
Note that Unity makes this somewhat confusing for beginners, because if the list is serialized Unity will create it for you automatically
Also for future reference, NullReferenceException is the most common error people encounter in C# and it's really a #๐ปโcode-beginner question
Suppose if a building is completed, you should change and update some stuff. Some of them are related to that building itself and the others are not like levelup, etc.
There are many ways to handle and manage it but I would like to know your approach. What do you think? Which one is more flexible and elegant, cleaner and modular?
When a building is completed, the list of jobs you should apply in your game is
-
The progress bar and icon should be hidden
-
The building model should change and be updated
-
play an SFX
-
play a particle effect
-
Levelup and increase xp
-
play a builder's animation
-
etc.
1- Pure event system. All components and systems listen to an event (here BuildingCompleted event) and update themselves
2- One specific class handles the procedures after completion of building by calling methods of those systems and components.
3- The mixture of them. In the building gameobject, there is a specific class to handle all changes related to that building (model, particle effect, sfx, progressbar, etc.) and for external systems, they listen to that completed event and ...
Hello, I'm working on an player stats system and I'd like to leverage SOs but not sure how to achieve what I have in mind.
I have a class for storing player bonuses such as:
public class ProfileManager : StaticInstance<ProfileManager>
{
public float MiningExperienceBonus;
public float MiningSpeedBonus;
Other scripts are referencing this class to know how much xp to give etc.. And bonuses can come from different sources (items, tech tree, ...)
Is there way to have a scriptable object like this that could somehow apply a bonus to a desired stat, without hardcoding the reference like this ProfileManager.instance.MiningExperienceBonus += value
public class Bonus : ScriptableObject
{
public string description;
public float value;
}
Yes, you can have a collection of bonus SOs.
Define a key id or enum for each bonus
public class Bonus : ScriptableObject
{
public BonusType Type;
public string description;
public float value;
}
yeah but I'm trying to avoid using an enum by using SO's
cause I might add and delete bonus types a lot and from experience, that gets messy quickly with enums
Then for example for items, you can get all bonus with type Item and then add them together + item.value
maybe I should just use a Dictionary<Bonus, float> in the profile manager instead ? and have a method within the SO to find the key in that dictionary and increment its value ?
it's rather the other way around, an item might have different bonuses
like an item that gives +5% mining experience and +10% mining speed for example
Your player listen to picked up event, then get the collection of bonuses
// player class
Dictionary<BonusType,int> _bonusDictionary;
public void OnItemPickedUp(Item item){
var bonuses = item.GetBonusCollection();
// update bonusDictionary based on.
}
In a loop
_bonusDictionary[type].value += bonues[type].value;
When an item is dropped, it is the opposite one, subtract it
_miningSpeed + _bonusDictionary[BonusType.MiningSpeedBonus]
Yeah that give me the following idea actually:
public class ProfileManager : StaticInstance<ProfileManager>
{
public Dictionary<string, float> bonuses = new();
}
And the SO as follows
public class Bonus : ScriptableObject
{
public void ApllyBonus(float _float)
{
ProfileManager.instance.bonuses[this.name] += _float;
}
}
And the item can then have a dictionary of Bonus SO's with values
I could even initialize the dictionary in awake by doing a Resources.LoadAll<Bonus> to fill the dictionary automatically based on bonuses
Yes but it is more elegant to change the direction of dependency
so it makes it pretty much fool proof
Bonus should not depend on anything
ah you mean to do it the other way around so that ProfileManager fetches the bonuses ?
like a foreach var item in PlayerEquipment add bonus from item ?
How can I emit a Space key press manually via code?
You do not, you wrap your code around the action of pressing a space bar and you emulate that.
It can take the form of a function or a something like a buffer.
Can someone explain why this => is used
[SerializeField] private InventoryItemData itemData
Then just 3 lines down you have this
public InventoryItemData ItemData => itemData
My first question is why does it have the => sign but also why have the exact same variable just different capitalization and use it interchangeably
Here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members#:~:text=Programming Guide).-,Read%2Donly%20properties,-You%20can%20use
Also, the reason you use a property instead of using directly the field is to keep the encapsulation and protect your implementation details.
https://www.geeksforgeeks.org/c-sharp-encapsulation/
So how do I know when I want to protect implementation details and make a new property
Always. You never directly expose a field outside. The idea is to control what people can do with your class.
By doing so you:
- Increase Readability.
- Increase Maintainability.
So how do I know when I switch between using the field and the property
You always use the property when accessing the field from the extern. For the intern, it is more of a style code question.
So the article says it just returns the value of it so does that mean ItemData now inherents from itemData
There is no inherents.
The [=>] is a like a lambda.
You could do:
public InventoryItemData ItemData => MyFunction()
Where MyFunction() return an ItemData
Do not overthink it, it really is just a different syntax for defining a property.
For me it is the difference between knowing what something is and knowing when to use it
What it is:
It is a way to define a read only property.
When to use it:
If you have a property that do not need to be set. (It really only a preference as there is other possible approach)
It's just a getter. This really isn't an advanced coding discussion
Hello! I wanted to ask something about Photon 2
I've been using it with Low Poly Shooter Pack 4.3.1 and so far it's worked like a charm, the only thing is that i can't figure out how to make the 3rd person models work. For example: One player can view another's player full body model and animations, weapon changes, jumping, crouching, etc.. But I can't see his first person model. Same thing goes for the other player. I need help on making this work
In case it's difficult to understand, currently if there are two players on the game scene, neither of them can see a full body model. they just see oddly tall floating hands
Hello there, does anybody have an example of using the MeshData API and procedural meshes? I could only find examples made for imported models and not on job system
can anyone tell me what this means "ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
"
i swear to god this error has been screwing my game for literally a week now
Not an advanced issue but it means you're trying to access an element that doesn't exist in an array or list
is there a way to find out whats causing the problem
Log the array/list length and the index you're trying to use
how do i do that
Do a bounds check and have the program spit out info to the console when you attempt to access an out of bounds value
nevermind
ill try solving it on my own
ive been trying to do it since 4am
@astral onyxThere's one way to solve it and it requires checking if you're in bounds within bounds of the size of the array
If you can't do that, then you need to understand how arrays work.
Alr
@astral onyxhttps://www.w3schools.com/cs/index.php
i actually solved the problem , turns it it was just one sneaky typo
For future reference, that's not an advanced problem. You should also stop copying stuff from youtube.
i wasnt copying anything btw
i had multiple lists and when trying to transfer objects some objects from one list went into another
and it all went downhill from there but i managed to fix it
When you want help next time, you also need to paste code.
understood
if I wanted to make TMPro.TextMeshProUGUI text selectable, so I could select the text in ways I can select text outside Unity, how would I go about it?
selectable as in like this:
Mark
Old stuff but probably relevant to your project's age https://forum.unity.com/threads/text-background-color-on-some-letters.454491/
Other such goodies http://digitalnativestudios.com/textmeshpro/docs/rich-text/ (not an https site so you may get red flags warning you if you're operating with an https only browser)
what I'm looking for is THIS selection functionality/behaviour:
Mesh exposes API that takes in native arrays for vertex buffer data, triangles, etc, so you really just need to populate the data in your job like usual, then feed them to the mesh.
does anybody know what is going on here?
it says its this line of code
restarting unity didnt help
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
how
The bot message just above has links
i guess i am stuck
i literally work for every step soooo long, cause it has so many errors always, this network untiy thing ๐ฅฒ
Having a configured code editor is required to get help here
Please proceed with the configuration now
which link should i press from these 5 above
Well, think about it for a momemt
What code editor are you using? That will eliminate 3 links out of the 5
Microsoft Visual studio
ou wait... i have the thing but its only not showing in this script i dont get it
i get red underlines where the code has problems usually
see
I dont even know why this code is poping up, i dont have this anywhere implemented this script
Do you have your own class named NetworkManager per chance? It might be picking up yours instead of the one in whatever networking stack you're using
I dont have any NetworkManager script or Object
Then your package failed to install properly. Close Unity, go to where it is on your computer, and remove the Library folder. Start Unity again and it'll regenerate the folder
Alr. il try that out. Thank you
sadly it happend the same again way
but when i delete the package everything works, but when downloaded again it stops working again ๐ฆ
Maybe that package depends on another one you don't have? If you're following a tutorial make sure you have everything
Its the only thing thats beeing done and for me it makes 0 sense why this is even poping up this code. This Code looks correct for me
But its like it isnt even connected with unity, something is just broke
What is even SceneLoaderWrapper?
Alr. i found something.
So after a make these 6 lines of code into a Comment. Everything just starts to work normally
i really dont know what the problem is, whatsoever, everything works now and i see no problems in the game while playing with other people. It probably is important in some way but if it doesnt affect me then i am fine
Event subscription. Your network manager will not be processing those callbacks as you've removed their functionality.
What do you mean?
Ou, so you mean it doesnt get information. I see
But, in which way would this help me? Where do i need to know these things.
Those lines of code subscribe functions that you've implemented (hopefully it was your code and not randomly copied stuff) and unsubscribe them on destroy.
An error would likely be generated if those functions were missing.
This is not my code. This is the code that you get after you download the package from unity, for network purposes
Commenting them out would remove the errors but not do whatever it was meant to be doing.
i know that, but sadly i really dont know what to change so it works, its very weird.
You're likely missing a dependency
wdym by dependency
Something that the code you're using needs that you don't have.
mhm, i see
It could be. But i dont know how to find what is missing
i needed this package because of this:
So other players could see the changes from other people
I can't help you either as I've got no clue what your project consists of.
Thanks still, very glad you tried to help me : )
Il just go on with commenting these 6 lines of code, and if there should be any kind of problems in the future then i guess il need to find out what it is.
If you are following a tutorial, you've likely missed a step else your project is missing a package or wasn't properly installed etc
I first had the problem that my unity didnt want to download the package trough the git link, and then i played something in the settings and then it worked. But maybe it has now problems downloading everything??? It could be, but i guess we will never know
And that problem took me over 1 hour as well. Thats why i am a bit frustrated
I can't find a solution from googling, but does anyone know how to implement a walls disappearing depending on rotation perspective in an isometric game? Video attached of problem. I'd like to have the close side wall disappear when the user is viewing.
I'm being dumb - long day. I just need to implement a script that checks rotation.y of the camera and if certain value turns off the mesh renderer
Ignore me
using UnityEngine;
public class WallViewRemove : MonoBehaviour
{
public float[] anglesToHide; // The list of angles to check against
private MeshRenderer meshRenderer; // The Mesh Renderer component of the attached wall object
public GameObject mainCamera; // The main camera in the scene
private void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
}
private void Update()
{
// Get the rotation.y of the mainCamera
float cameraAngle = mainCamera.transform.rotation.eulerAngles.y;
Debug.Log(cameraAngle);
// Check if the cameraAngle is in the anglesToHide array
bool isHidden = false;
foreach (float angle in anglesToHide)
{
if (cameraAngle == angle)
{
isHidden = true;
}
}
// Set the wall to be visible or invisible depending on the camera angle
meshRenderer.forceRenderingOff =
isHidden;
}
}
``` if anyone wondered.
Btw, Renderer has a forceRenderingOff property, which should be faster than setting the enabled property.
meshRenderer.forceRenderingOff = isHidden; ? computationally quicker you mean?
Yeah, it's just a flag, whereas "enable" likely does more work
I love ReSharper so much
Does [BurstCompile] honours [MethodImpl(MethodImplOptions.AggressiveInlining)]?
It should force inlining if it's not already doing so. You can check the Burst compiled output to check the difference.
I am wanting to make sure. Are Unity compiled games able to run via the command-line and if so, do all print statements and variants of Debug.Log output to the command line?
Debug.Log are stripped from build.
So print isn't?
print is just a wrapper around Debug.Log, so yes they are stripped.
I see. Is there a way to output a message to the command prompt if the game is ran from it?
Unity is not really made for Command Prompt console. It can run in headless mode for server, but it does not accept input.
Alright, thank you.
If you explain what you are trying to do we could maybe suggest other alternative.
I am creating an online multiplayer game. I am making it a Client-Server architecture with players able to utilize the Dedicated Server build to host their own servers. I seen popular games, such as Rust and Unturned, output messages into the Command Prompt when running in Batched mode. I am hoping to find a way to utilize that logging feature to print messages to the Command Prompt / Command Line for players who are hosting servers.
They are running in headless mode, I think you can enable Debug.Log() in a build, but you might want to do your own logger for that.
I have a camera controller script with a large number of values, and I would like to be able to swap them at runtime, ideally with some way to restore defaults. (eg. entering a scripted sequence which involves a clamped camera angle) I have considered scriptable objects to store the camera data, but can't find a good way to copy the data from those scriptable objects into the fields of the script without hard coding every property I want swapped.
Is there a good way to do this?
Hey, I'm currently profiling the server build for my game (so no graphics) but for some reason WaitForTargetFPS is using 30+ms. I know that WaitForTargetFPS usually means VSync, but I'm confused on why that would be happening on a server build. I have disabled VSync within the quality settings and set Application.targetFrameRate to 0 but still with no luck. What's weird is that it only occurs on the server build and not the main client build? (which has graphics). My Unity version is: 2021.3.15f1
I do not know what is your issue. However, is there any reason why a server needs to run more than 30FPS ?
And the value is suppose to be -1, not 0.
https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html
You should use Cinemachine to achieve what you want. Cinemachine use what we call Virtual Camera to setup multiple "fake" Camera which is then use to modify the current camera.
better than rider? considering another IDE because rider's glitchy
There is only Visual Studio/Visual Studio Code and Rider as IDE available for Unity.
is this new? had to overload the Debug class before to get rid of them
Depends on when you are referring. I know at some point you had to do that.
Rider is running resharper itself, what do you find glitchy about it?
Debug.Log is not stripped ๐ค
Yeah, I looked back it seem it is not. I'm using a variant which is. ๐คฆ
You can exclude them from being reported though.
tons of problems, latest are autosave not working every time & double listing declaration. one update fixes one thing and breaks another.
I have no idea what those mean. Though I don't use autosave
sorry I meant rider
Rider is the best out of everything imo
The only thing that I wish it did better is other minor IntelliJ-family features like rendering documentation comments inline and stuff.
Rider is a godsend
autosave always works for me. I'm on 2023.1.1
you know what, it functions on my laptop and not on my desktop
have you tried factory resetting your preferences
physics interpolation happens when? it's not in the life cycle graph
no but i share rider preference across machines
Hello I am trying to find a way to use ECS for a topdown game with Unity, as currently I can not get more then 1.5k enemies to spawn with rigidbodies and collision, most tutorials no longer work with the current version of ECS, is there any any tutorials or guides for how to set up a basic ECS system for the current version of unity and ECS?
11 on the laptop
The docs have a basic example https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/ecs-workflow.html
oh sweet I will have a look at it and see if I can get a basic set up going
bah, the "tanks" tutorial link is broken
I used this to get to grips with the ECS. It was extremely helpful.
wait, this has gotten rephrased a fair bit since I used it...
i'm pretty sure it used to have way more step-by-step content
ah, yes, it did
this is from before Entities 1.0.0
so it may no longer be accurate
Yeah I ended up following the 1.0 manual, got some entities to spawn, honestly still quite lost mainly due to all the new syntax and also the entity hierarchy system, I think I have the basics, it seems as though the last update to the project you posted was 4 months ago so I think most of it still fits, I will download it and see how they have set it up
well managed to get a few thousand spawned, albeit in the same spot/location, now to try and figure out how to get the entities to move, as spawning them with a basic enemy script doesn't seem to make them move.
it's been a half year since I really dug through the system
the core idea is that you'll need to write a system that operates on entities with the appropriate components
e.g. it finds every entity with a "movement" component and a "transform" component and moves them forward a little
this is ultra-efficient because all of the entities are grouped by what components they have
oh ok so I create another entity component that will be attached to all enemy entities for both movement and transform or can they be the same component?
components are generally single-purpose
or you just dump the lot and write your own. This has 2 major benefits
- It will work
- It will not change randomly
they describe an attribute of an entity
write my own what ?
ECS
given that the Entities package is now up to a 1.0 release, it might be a ~little~ less turbulent
I just want a system to spawn 3000 enemies with rigid bodies for 2D top down game, have written a game in Godot and could not get it too deal with anything over 1500 rigid bodies, only thing in terms of game engines I have seen do what I need to do is this ECS and DOTS systems, but I am not really a great coder
Dream on, this is Unity. They have not produced a decent subsystem in the last 6 years that they have not consistently broken
yes I noticed from a fresh build using a 2022 version of unity and installing the packages I get all types of errors, quite odd to have official packages be broken from fresh install/builds, but currently there is nothing else on the market I can use besides really obscure things like Rust Bevy engine
depending on what you actually want to do with those 3k agents, entities might also struggle with it. Although it can make computation considerably less wasteful, it still has to deal with the hard facts of N^2 complexity
assuming all agents talk to all agents, at least
a good physics system will efficiently handle collisions between them
well, complexity is a space, its not whats actually happening, hence "depends on the specifics"
and what a "good physics systems" can do is still is bounded by the desires and ability of the programmer
there is no magic way to solve N:N collisions
nothing to crazy, just basic collision between each other and the ability to have them push each other around, but yeah having it iterate using a loop through each enemy makes it hard, considering from the performance tests I have seen I am hoping the ECS will be just enough as Godot almost got there with only minor changes( I used its internal API for physics and rendering not the scripting language version)
this is way more computationally expensive than you might think
the entire point of a physics engine is to efficiently solve collisions between many objects
they do a pretty darn good job of it, too
rejecting most impossible collisions and then testing just the ones that might actually have happened
you are looking at the wrong part of it, ofc it can detect collisions efficiently, but the depenetration is a wholly separate problem
if you have a mass of colliders that can all push each other and are in contact, you quickly run out of iterations in the solver
and there is just no way to fix that, its inherently a computationally hard problem
there are other ways to solve it, for example via tensors or flow simulation, boids (steering/avoidance) etc. but not via generic collision depenetration
I'm just trying to make a horde survival game with alot of enemies, set myself a goal of 3000 enemies who knew it would be this difficult lol
i'd say you should be looking at a steering/avoidance approach via entities, not via physics
yeah, I see what you're getting at
yeah I think so, I mean I don't need them to simulate physics 1:1 but just the illusion aka certain weapons can push them
if you use steering/avoidance, you can actually do this without entities, you can use data oriented programming/jobs/vectorization anywhere to speed up your calculations
if you just pile up 3,000 rigidbodies, you might get very wonky behavior
unity can handle about 2000 before it starts getting weird, just with a basic set up, no ECS or anything like that, with an enemyController that controls them all
yeah, if your agents are simple and have no physics, you can update 3k gameobject positions each frame
how would I want to go about the collision between them? I don't want them to pierce through each other
steering and avoidance
as in they don't have colliders, they just stop moving if they are going to hit and if they do hit they move out of each other ?
you can never solve the collisions perfectly, so you need an approach that produces an acceptable result, cowd simulation is one
they can have trigger colliders to detect their proximity, maybe sized to find whatever is withing 2 seconds of movement, and then steer themselves to home in on a target, while avoiding any other agents nearby, and additionaly they may exhibit squad movement by also following the movement of nearby agents
you'd do this iteratively, updating all of them each frame
this then creates emergent crowd movement
"data oriented design" generally means that you pack data for many things together
instead of having 3,000 random objects on the heap
this is a big part of what makes the whole ECS performant
yeah this is similar to the system I made in Godot, it just wasn't very performant using c# with godot so I switched back to unity , quite a big difference in terms of complexity of the system I was using though
there is this tutorial which seems to deal with the basic idea https://learn.unity.com/project/crowd-simulation
In this project you will be working with a high number of agents to simulate crowd behaviour. You will discover how patterns of movement can be formed from the simpliest of rules that mimic crowd behaviour in the real world. By the end you will have created a crowded city street scene with humanoid characters walking along a pavement and avoid...
so instead of Rigid Bodies I would be using kinematic bodies in essence ?
neat, I'll need to look into that at some point
well here is 10k easily spawned enemies, bit of a problem with the movement though lol, seems to only be moving the most recent creation slightly
you have a few errors there...
yeah they been there before I even started coding so I just sorta accepted them as part of base unity
pretty sure this one isn't, though...
oh yeah thats just the counter, theres probably around 5 or so to do with me and not the base packages and how they work with each other/obscure project settings not tuned from default, but currently none of them seem to break any of the code I am writing so no point wasting time on fixing something I might not even be using in 30 minutes from now lol
its funny cause it says it cant read from it but it still does anyway
Hello, im with a metroidvania project, i want scale x * -1( scale X = 5 * -1 = -5) but dont function, someone can help me ? (https://dontpad.com/Metroid for the complete code)
Hello
What would be the best way to schedule dispatch calls of a compute shader so that there's only one or two running at the same time?
I have to dispatch a compute shader, let's say 100 times, I would like to do it in packs of 5, so that the GPU stays busy, but not with memory overload
Not sure how could I schedule them, like in a queue or something
Is there any way to make multithreaded prefab spawn? Main threaded instansiating gives me freezes and fps drops.
You can load them on a background thread but init and instantiating are main thread only
thanks
are you spawning and destroying the same type of objects often?
ima just record a vid.
i am spawning but not destroying
rooms that are not in range are just being disabled
Okay, I want the player to face the other way; he's looking this way and he keeps looking in the same direction even when I press the button to go the other way, do you understand?
For JSON parsing in C#/Unity, do you have to explicitly define the class you want to parse into? I'd like to be able to handle any arbitrary data, but it seems like that isn't possible?
You can use json.net to parse a json string into a xpath like structure
For example my websocket schema is usually:
{
"type": "CharacterMoveEvent",
"data": {
...
}
}```
where the message gets routed based on type
Looks like a discriminated union to me.
Is json.net builtin to unity?
Yes
I'm not familar, what's that?
A wrapper used to handle multiple types with one structure
Basically what you have there with your type annotation and untyped data field
Json.NET should have support for DU since it's pretty prevalent in web API.
But if not you can always just do your own primitive version of it with JsonUtility.
I want the player to face the other way; he's looking this way and he keeps looking in the same direction even when I press the button to go the other way, do you understand?
this is not an advanced topic. if you still need help with this then ask for help in #๐ปโcode-beginner again
Ended up getting it installed through the UPM
The type or namespace name 'WebSocketEvent' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp] I don't quite know how namespaces work in C#/Unity
{
public abstract class WebSocketEvent
{
public string Type { get; set; }
}
[Serializable]
public class MoveEvent : WebSocketEvent
{
public string CharacterId { get; set; }
public Vector3 TargetPosition { get; set; }
}
}```
using WebSocketEvents; should work right?
You canโt instantiate abstract classes, maybe thatโs why
yes. unless of course you still have issues with assembly definitions that you aren't expecting ๐
I don't know that much about this, but these are my own custom classes and namespace with no assembly so it shouldn't be an issue, right?
removed the abstract but it still doesn't recognize the namespace
did you put them in a folder that has an assembly definition in it again like you did last time?
no
is this error only showing in vs code or do you see it in the unity console as well
Are you sure that websocket events are in the websocketevents namespace?
Your websocket client doesn't seem to be in a namespace
{
public class WebSocketEvent
{
public string Type { get; set; }
}
[Serializable]
public class MoveEvent : WebSocketEvent
{
public string CharacterId { get; set; }
public Vector3 TargetPosition { get; set; }
}
}```
Sometimes you also have to let unity reload for it to find new types
Esp in vscode
Also can't you get vscode to automatically add the using when you are attempting to use the type?
Unsure if it matters but your client is not in a namespace either
no the vscode quick solutions don't show it with my unity setup for some reason
Ide misconfigured
Is your player made our of two semi circles and a rectangle?
If so, just split the screen to those three parts and the rest just some simple geometry math.
What is the best way to render a lot of icons in screen space unity UI?
Using a canvas causes awful giant spike when moving camera (icons should move as well, set the position)
When using anchoredposition and set it, it is OK but when setting anchored max and min, it causes spike
Im gonna send it again since it got lost
What would be the best way to schedule dispatch calls of a compute shader so that there's only one or two running at the same time?
I have to dispatch a compute shader, let's say 100 times, I would like to do it in packs of 5, so that the GPU stays busy, but not with memory overload
Not sure how could I schedule them, like in a queue or something
I tried using a graphics fence, but I'm running other compute shaders, that don't need scheduling, that would trigger the fence too
There is gonna be only one running at the time. A GPU can't possibly run 2 programs(shaders) at the same time. Some GPU could potentially run compute and graphics shaders at the same time(I think PS5 is able to do that). But in most cases, shaders run one at a time.
Afaik, a dispatch is a blocking call, waiting on the CPU for the GPU to complete it's work.
There's an async dispatch that would queue the dispatches for execution asynchronously without blocking the CPU. I don't remember the exact API though.
Okay, so what I would like to do then is to dispatch less compute shaders, so that the cpu stays less blocked, process a frame, and then run the other ones
An async dispatch would not stall the CPU?
No. As it wouldn't wait for the shader to complete. It might still cause unity loop to stall, as it needs to use the GPU too(for frame rendering)
Mmmm, then it wouldn't solve the issue. I would like to spread them in multiple frames. But wait, I'm having the same convo in #archived-shaders, let's talk there
I think it's called AsyncGPUReadback
How would someone go about adding a physics collider to a enemyPrefab that is being created and controlled by an ECS? I can make them spawn and follow the player but I have yet to figure out the correct way to add collision onto them, like a rigid body.
ive been using navmesh but the navmesh agent variables arent doing anything. I'm trying to make the agent not slow down when getting near to the destination using:
navMeshAgent.stoppingDistance = 0.0001f;
and i set auto braking to false but the agent still slows when near the destination... Can anybody help me fix this?
i want it to move at the same agent.speed
right until it hits the target destination
im changing the agent.speed and agent.acceleration in code every once in a while
i set acceleration and speed to the same value all the time
Is Someone Into States MAchines
I'm making a unity 2D game with ragdoll physics. The game revolves around a stickman which is able to aim weapons, where the weapons rotate towards the mouse position. An example issue I'm facing when aiming a weapon is that if the mouse is quickly moved from the right, then over the player ending in the left side of the screen, the player's rotation will be calculated wrong, resulting in the players arms being bent, no longer following the mouse correctly. How can this issue be resolved?
Attached is a video demonstrating the issue, as my articulate skills are not the best
For more information feel free to ask
Please @me
Do not update if the mouse is too close to your given point ?
I have tried adding a deadzone, where if the mouse enters the players center, the arms will simply stay at the last rotation. But this doesn't solve the issue for some reason...
And why does it not solve the situation ?
How would I know? Perhaps the code is wrong
I mean, this is kinda your job to know. This is called debugging...
If you do not, then you need to work to know.
Well I did some debugging by drawing the mouse position with gizmos. And seems the issue is that if the mouse position is on the right and you move it cross the center of the player, the position kinda just teleports to the other side, causing the limbs to move fast in order to reach the target making the issue occur.
Then maybe you could try to make move it slower ?
I have tried that without luck
This is how I move the arms: ```csharp
if (armsActive)
{
Vector3 difference = Target - (Vector2)transform.position;
float rotationZ = Mathf.Atan2(difference.x, -difference.y) * Mathf.Rad2Deg;
rotationZ += rotationOffset;
lastRotation = rotationZ;
rb.MoveRotation(Mathf.LerpAngle(rb.rotation, rotationZ, speed * Time.deltaTime));
}
If the speed is too low, his arms will simply rest along his body and he wont be able to hold the weapon up
@signal moth
Anyway, we cannot continue this as it is an advance channel. If you want more advance on how to debug, feel free to reach for #๐ปโcode-beginner or #archived-code-general. I doubt there is anyone here that could directly help you with your issue, you probably know more on your problem then all of us. However, If I were you, I would try to come up with a better idea to make your character walk/aim. I would look how we can couple Animation and a Ragdoll. (Have something of a lerp between both, like an Additive Animation). This way, you would have a better control on your character. With luck, you might even solve your issue.
I tried to find some resource, but it seems there is a lack of it. Maybe someone else in the discord would be able to find something.
An other thing, might be inverse kinematic.
Any funky ideas on how to mark some Unity API's as non valid just for compilation sake? Mainly, GetComponent<T> and FindObjectOfType<T>
Example vanilla GetComponent<T> is slightly doable, by hiding the original GetComponent<T> and marking it as obsolete with error throwing on. But, still, GameObject.GetComponent<T> and Component.GetComponent<T> are still considered as valid.
Context is a little broad, but this is what the requirement is ๐
Have better code review policies...
Otherwise, you might want to look into an Analyzer such as https://github.com/microsoft/Microsoft.Unity.Analyzers. I have never done that, but I know it might be possible. (Same if I would recommend to not do this as it has a layer of complexity that would make your project harder to maintain)
Can also use a test in your CI/CD that looks anything that is GetComponent or FindObjectOfType.
Err, its actually not for the main project, but for the output of the project a unity plugin which is supposed to be a place where people can write code. We don't currently support generics in that so that's why I'd like a way to disable it
A good documentation would suffice in my opinion.
Its a "enforced" suggestion to the user of this product to not use such API's. If they follow it, there's no problem at all. But I'd like to remove the chance altogether, since Unity still considers it as valid code
You could also develop a plugin for VS or Rider.
Too much money and effort ๐
I'll look into writing an analyzer that's somehow integrated with unity
This is maybe even harder then a plugin.
Feel free to test it, do not take my words for it. However, If I were you I would consider having a well layout documentation.
I'm having trouble getting some entities I have spawned to have any type of collision/colliders/rigidbodies or whatever unity.physics requires them to be, have an ECS system using entities,
currently my enemies are being spawned and also moved easily but I have no type collision, unsure if I am doing the component adding incorrectly(they do show up in the entity viewer) or if there is some other thing I have to do to enable them, here is my code :
class EnemyBaker : Baker<EnemyAuthoring>
{
public override void Bake(EnemyAuthoring authoring)
{
var entity = GetEntity(TransformUsageFlags.None);
AddComponent(entity, new Enemy
{
CurrentPosition = float3.zero,
TargetPosition = authoring.TargetPosition,
Entity = entity,
PhysicsVelocity = new PhysicsVelocity { Linear = float3.zero },
PhysicsMass = PhysicsMass.CreateDynamic(MassProperties.UnitSphere, 1.0f),
PhysicsCollider = new PhysicsCollider { Value = Unity.Physics.SphereCollider.Create(new SphereGeometry { Radius = 8.0f, Center = float3.zero }) }
});
Ye. Just trying this out in my downtime. thanks for your response!
for specific project?
yep
cecil?
you can just slap the attributes directly on the methods with it
but youd have to reapply for each unity version upgrade
small cli updater will suffice
Something like this? https://blog.aspiresys.pl/technology/static-code-analysis-with-mono-cecil/
Hmm, supposing this works, this would be project wide, right? And I'm assuming its not Unity installation wide. Do you know if how this would interact with precompiled plugin assemblies using the API I just marked obsolete using cecil?
@plucky laurel
unity install since its copying asmb from editor dir, but you can mod the cached ones in library instead
no idea btw
possibly wont throw if they are precomp since it will only copy them
afaik unity added analyzers
some way to integrate them for unity specifically
its just can be even more effort than cecil
because of all the possible edge cases
maintenance burden
Yeah I've been looking at them and looks like too much effort to even see a sliver of result
Someone tried it in 2014, it seems https://groups.google.com/g/mono-cecil/c/wfawmREN6uo?pli=1
yeah i wouldnt take that seriously
could have missed something, did something wrong, misunderstood whats copied where etc
could be just a fluke
lol unity changed so much since 4.6
i know for a fact cecil is used in prod and high profile plugins by this day
now i want to
public ~~sealed ~~class GameObject
and see where it can take me
probably somewhere unreal
Could also look into this https://github.com/dotnet/roslyn-analyzers#microsoftcodeanalysisbannedapianalyzers
Never used it, but seems to be just configure which APIs you want to ban and that's all.
lol, how? I'm stuck on the first step. From what I can tell, Unity uses the ones in the install path. There's no local project copy of for starters lets say UnityEngine.CoreModule.dll
Did you look in Library ?
Oh. My bad. I was looking in Library/ScriptAssembles
Hmm, I think that's only populated when the project is built
got a network problem:
somehow my outgoing packet rate is framerate dependent... if vsync (60hz) is enabled the outgoing udp packet freq is ~60hz, if vsync is disabled the packet freq is ~ 250hz, as desired.
Udp sockets are fed by seperate threads and threads are fed by the physics update rate, which is 250hz.
any ideas ?
How should I structure my hierarchy? I have like 40 worms with 60 moving parts each. Physics.SyncColliderTransform takes up several times more time to process than everything else in the game combined. The worm's hierarchy I think is about 7 transforms deep. Any tips? Appreciated.
There is this article but link to the described tool doesn't work, do you know if it's any useful and if yes then how to get it?
https://thegamedev.guru/unity-performance/scene-hierarchy-optimization/
Hmm see if any of your transforms have non-uniform scale. I think that can cause SyncColliderTransforms to take a lot of time
Actually, none of them is, does it really matter much?
It was a problem for me, but if thats not the case here then nevermind
physics update doesn't run separately, it runs multiple times per frame to catch up
this website is grating to read
this explains things
haha, real talk - every sentence is like weirdly dramatised clickbait
breathless to the end
it's like i'm getting beaten unconscious on the set of an infomercial
btw is the physics code somehere opensourced ? i'd love to integrate some physics deltas
some whats
In the docs about plugin default settings (https://docs.unity3d.com/Manual/PluginInspector.html) , what do they mean about the part of the path in brackets? Is it that you're supposed to create a subfolder simply named /x64 etc? Or do they mean adding that to the end of the subfolder's path like for example /myplugin x64?
ok so like \plugins\myplugin x64\?
no, it'd be like Assets/Foo/Bar/Plugins/x86/whatever
the key part being everything up to and including x86
ah ok perfect. thanks
Will this list be garbage collected after returning ?
public List<Upgrade> GetActiveUpgrades()
{
List<Upgrade> list = new();
foreach (var upgradeSlot in upgradeSlots)
{
list.Add(upgradeSlot.LastPurchasedUpgrade());
}
return list;
}
you're returning it, so presumably you'll still have a reference to it. which means it wouldn't get GC'd
so it will get GC'd when the other method invoking it won't need it anymore ?
not sure how to properly dipose of it in this scenario
it will get GC'd sometime after it is no longer referenced by anything that isn't also getting GC'd
you don't need to manually dispose of your List<T> objects. that's what the GC is for (it also doesn't implement IDisposable anyway)
as with literally any other reference type, when you no longer need it in memory you just set all references to it to null so the GC will take care of it for you
How do I stop unity's name and hideFlags variables from being saved into my json file?
"name": "Gunname",
"hideFlags": 0
I tried
[JsonIgnore] public string name;
[JsonIgnore] public HideFlags hideFlags;
yes
welp, i had to hack an opt-in in source due to such issues
what's your get around then
dont remember, but opt-in solved it
gotcha
yea thanks this will be much better
generally I just don't directly serialize things that derive from UnityEngine.Object in the first place.
But - Opt-In is a really good idea in general
well yea i was just saving the whole scriptable object into the json file which is fine but it also came with name and hideFlags
How can i update all tiles on the tilemap in another thread to save speed
I have a 100 x 100 tiles map, and I am changing the color of all tiles, however, as you can understand, it is quite costly
can't access the tilemap API off the main thread, just like most of the rest of the Unity API
The Tilemap itself has a color property, if you're trying to tint all the tiles the same way
negative, individually
Make your calculations on the other thread and only assign the properties on the main thread. Something like a command buffer could be used.
My calculations are quite fast, I've measured them, it's less than 0 seconds for the whole map.
It's the refreshalltiles that is killing me
less than 0 seconds? ๐
are all of the tiles visible at the same time? if not, you could update only the visible tiles and spread the rest of the updates over a few frames. then you can just refresh the tiles you've changed that frame instead of all of them
onenable is called when the scriptable object is loaded -- what does loaded mean?
when it is loaded into memory. for a scriptable object asset what will be when you first create the asset, when you relaunch the editor, in a build it will probably be either when the build is launched or when something that references it is loaded (like on scene start or whatever). otherwise it will be when you call CreateInstance
gotcha, so reseting a value in onenable is a good place. that or setting the variable as [NonSerialized] which is prob better
I'm trying to move a player that I made into an ECS, I can get it to spawn but I can't seem to get it to move from a movement key
Did you create a system that would move it based on controls?
I think I did but I do not know if I have done something wrong, it is able to move my enemy but when I tried implement the player controls I don't think it is taking the input
Hi all, does anyone have any advice on how to do number recognition in Unity? So e.g. if a player/user draws a number on their mobile, I want to recognise which number it is, or indeed recognise that it's not a number.
The best my searching brings up is this: https://assetstore.unity.com/packages/tools/ai/noedify-easy-neural-networks-161940 which you need to train yourself. I would have thought it was a pretty standard problem, but I can't find much. Any advice?!
You might be interested in https://developers.google.com/ml-kit.
An alternative would be to use an external API.
Ah great, thanks!
You can also train the model externally, and your Unity game only needs to run the trained model.
If the model doesn't need to interact with Unity or your game in any specific way, you can train it outside of Unity
And there are probably plenty pre trained digit recognition models out there, because practically every entry to machine learning uses this exact problem with MNIST dataset.
Or this https://depts.washington.edu/acelab/proj/dollar/pdollar.html , but me personally Ive had the most success with jaccard similarity index
hello there, I know this question has to be posted in #archived-shaders channel, I already did, but that channels remains unactive for most of the day, so Im gonna ask here.
I want to learn compute shaders as they seem way more beneficial than using jobs for my current project, but the problem I have right now is that all the guides or tutorials use compute shaders with a texture rather than processing values or returning values such as floats or ints, so does anyone here knows a tutorial that does not uses textures for compute shaders?
Why does this loop seem to execute instantly, and not respect the time ?
The while loop condition is false first hand, or, the player isn't alive
Or, duration is lower than 0
Or, an exception occurs
Or, the coroutine was not started properly with StartCoroutine
Debugging required. You need to log the values of these variables or even better, place a breakpoint and step through the code line by line, inspecting the code flow and the values.
is here something wrong
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public float speed;
private float Move;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb= GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move= Input.GetAxis("Horizontal");
rb.velocity = new Vector2(speed * Move, rb.velocity.y);
}
}
cuz i want to add it to compoments and it dosent work
this is 100% not advanced. please move your question to #๐ปโcode-beginner
and share the !code correctly
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
somebody can take a look why my player keeps bouncing? https://hatebin.com/iibztmkffr
It has something to do with the offSet````Vector3 offset = playerCollider.bounds.extents.y * Vector3.up;```
Is OnCollisionEnter being executed? Also this very much looks like code generated by ChatGPT seeing one comment for almost each line of code
Because it is, i only explain the mechanics i want.
this is spam
and the rules explicitly forbid asking questions based on AI spam...
Yeah all that is pretty nonsensical
Do you want us to write the code for you? Well your AI is pretty much doing it right now
What spam i ask a question about my code.
AI generated content is spam.
it is often nonsense, yet it looks plausible enough to make your pay attention
Just a code question.
We ask that you do not [...] Ask or answer questions using unverified AI-generated responses.
About why my character keeps bouncing
Well you have code for that, better post it instead of some autogen'd code
Unless...
I just posted the code.
you are asking us to comprehend something that was randomly stapled together by a GPU
Oke
doesnt like answers: hops channels
Anyone experienced got a minute to help me with some code?
Lord almighty
๐ซ
Yeah I suggested something in that thread, they proceeded to ignore it, and just closed it?
Like if you don't want help just say so lol
Well you're not doing anything I tell you so you can't know
Eh you'll find out eventually that it's your code, but you won't admit it and the cycle will repeat
I've done things you've told me. And have told you so. You're taking it personally and getting offended. I need someone more experienced to look at my code.
haha
Your coroutine might just be getting executed twice in a short succession, you should add some code that checks if it isn't running already, and it it is, throw an exception for debugging purposes
This, I suggested this in the thread
Can you show me the results of that?
Also "needs someone more experienced", is this some kind of dunning-kruger effect?
Dude, you said 'you're not doing anything I tell you' which is categorically false and you can go check the chat above yourself
Debug results please
that's the point I'd rather move on to someone else with a more reality based type of reasoning
@plain abyss someone you know needs that reality check
Oh this fuckin guy
Yeah that sums it up
Reminder
oh boy
haha you guys are a fun crowd
Apparently I'm not "experienced enough" to solve their "cursed code" issue
Maybe call that exorcist after all
I've got actual work to do today some I'm afraid someone else will have to babysit them this time
when you are seeking out completely free help from people, you should really humor them when try ask you to do something
Spent a huge amount of time in the thread I pictured convincing them to do basic debugging steps because they "knew that wasn't the problem". ||Narrator: It was||
hey digi, while you're here, have you considered adding a new category to your counter: Tutorial was actually ChatGPT
๐คฆโโ๏ธ
it's just categorically true, I don't think you can help me
You're just blatantly trolling at this point, everyone ignore!
Not if you don't listen, a lot of people here are professionals they do this for their jobs and and shipped titles
Your problems are not going to be outside of those capabilities
Yeah probably not. Better quit forever then.
Well I don't know how to act on 'you're note debugging hard enough' my best approach is to debug log variables and narrow down the problem until I figure out what's the issue
Oh good you're using logs now. Getting you to do that was like pulling teeth. Glad you've at least assimilated that
putting you on ignore, you do nothing but shit talk and it's pretty tiring
have you considered that if you don't know what to do in order to debug something maybe instead of immediately telling other people they can't help you instead asking "what would you recommend i do to debug this" and then just do what they say?
I don't care about arguing I care about finding out what's up with my code. You scroll up and re-read the conversation as much as you like
Yeah that means "nowhere" ๐ฟ
don't let your ego get the best of you
I'll return that statement to yourself
'you do nothing I tell you'
Let's not expand this useless conversation here
and you keep bringing up my previous thread and pinging digiholic to join in with your shit talk
because you're offended that I think you cannot help
you're ego is obviously hurt so you lash out
super obvious
<@&502884371011731486> spam
anyway I'm moving on to someone who can help
Nah I was brought in because I'm the only person patient enough to deal with your bullshit but I'm actually on a clock today and I don't have time
So I'm afraid you're outta luck
@hexed meteor In the future, your questions belong in #๐ปโcode-beginner, use that channel. Secondly, this is your first and last warning about resisting help here you don't like or don't want to implement. Every time you post here, it's always an issue, so putting this on record so that the next time it happens you can't complain when you're muted. ๐
Sup! Having a really difficult time trying to figure out how to handle weapons.
I can switch weapons, shoot an enemy, apply different damage valued based on the weapon. I use scriptableObjects to store a bit of information about the weapon.
The issue I am having is architecting a solution to store bullets fired from a magazine , switching weapons and keeping track and possibly switching to other weapons later.
I would love some idea or input on how to approach I guess weapon state?
Side note: Not looking for code, I think I am more looking at how to possibly go about tackling the solution.
Not an advanced question.
What's so hard about decrementing a magazine counter?
Like you practically already know what to do.
Sounds like they don't have a place to store individual item state.
@fallow dune Straightforward approach is to have some sort of item class that represents a single item instance and all of its state. The issue with just ScriptableObjects is that by default they tend to represent all items of a given type, so you don't have the per instance data.
That's what I did in one of my projects. Weapons on the ground have a pickup script attached which exposes common properties to apply on the weapon when it's equipped (on instantiate). Then when the weapon is dropped I can instantiate a pickup back, store the state it's in into the pickup script, and it's ready to be picked up again in the state it was left off. Switching weapons was as simple as disabling the weapon at the right time, "freezing" its state
As for writing a central ammo system, a really clean way is to use enums as array indexes. myCharacterAmmo[_9mmAmmo].
If your ammo can be complex, you can also just also treat them as items
Yeah, you could stack some modifiers on them like damage boost or increased range, in a list of modifiers you can edit from the Inspector
Another script can then loop through these and apply the mods to whatever property is relevant
Why are my tilesmaps generating the colors in this shape?
Kinda feels like something's wrong with the tile scaling.
So i thought, but doesnt seem to be the case
Non uniform scaling perhaps?
Place one tile and take a screenshot
ah yes
everything is on 1 tho
It could be that your sprites don't have the right ppu
does this object have any parents?
Or was it upp?๐ค
Certainly just seems like the hexes are double sized
children are good
and then there's just some z-fighting happening
this,
I was using the default hex, i assumed the ppu would be good
it was at the default 100 ๐ฆ
instead of 256
What's "the default hex"?๐ค
The one that unity provides, standard white hex
Did it provide such a sprite by default?
Hexes look good, thanks @untold moth
no, i dragged and dropped it
Okay then.
boom.
I'm creating NavMeshLinkDatas at runtime and setting the NavMeshLinkData.owner value to the monobehaviour that create them...
At NavMeshAgent.currentOffMeshLinkData, how can I get that owner? There is no owner in OffMeshLinkData type.
can you make your own class that inherits NavMeshLinkData and create a getter for the owner?
NavMeshAgent.navMeshOwner. according to gooogle, it's this
NavMeshLinkData is a struct so no inheritance.
but also i'm not even seeing that it has an owner property ๐ค
oh actually it's the NavMeshLinkInstance that has the owner property
have the "advanced" navmesh things been put into the base engine yet? perhaps they're using that
from the github repo
yeah, in the AI Navigation package
it left experimental in...2022? or maybe 2021, i forget
NavMeshDataInstance has an owner property. You get that instance when you pass a NavMeshLinkData to NavMesh.AddLink method
Hi guys! I need help with something. So currently, I'm experiencing a bug wherein multiple instances of a controller button press via Oculus Quest 2 is inputted for every one press of a controller button. I'm using InputDevice.TryGetFeatureValue() and CommonUsages to extract the input signals coming from the Oculus Quest 2 controller button presses. Would you guys have any ideas on how I can make a single button press only translate to a single input signal in Unity?
Are you just not distinguishing in your code between the action phases? (Started, performed, canceled)?
I tried doing that but it still keeps on occurring which is why I'm asking for possible ideas
how do I learn AI? I want to make something complex. Right now I only know how a* works and I experimented a little. I need a course or maybe see how people are remaking other game's ai. I might want learn how to make my own navmesh later. Should I try to get into machine learning?
depends what "something complex" means. machine learning can be useful but it's not solution to everything
You can always revert to OVRInput.GetDown(OVRInput.Button.One);
let's say I want a unit to consider 2 decisions at the same time in a real time game. The first would be attacking the player and second staying alive. And i want it to find a compromise each time. how would i begin to do that?
Maybe look into Utility AI and Planning
thanks i'll look into it. more advice would be helpful.
How do I make an array of arrays in job?
Kinda NativeArray<NativeArray<Vector3>>
This channel goes over a lot of different AI concepts. This particular video is about Utility AI
https://m.youtube.com/watch?v=p3Jbp2cZg3Q&pp=ygUKWXRpbGl0eSBhaQ%3D%3D
And the vid descriptions usually have links to resources for further reading
GOAP is another concept to look into
What are you trying to do?
Well, a parallel job working with arrays inside my objects
someone can help me with my game mechanic
trying to let me player which is a smalle sphere stick to the bigger one Vector3 newPosition = gameObject.transform.position + (surfaceNormal * Time.fixedDeltaTime);
What's happening and what's supposed to happen?
Doesn't look like an advance question btw, maybe try #๐ปโcode-beginner
Yea was considering this as well. Thanks for this!
Can I simulate a Collider without the Component? So that I have to do it every FixedUpdate
i guess you could do physics queries
I need specifically others to be able to detect the Collider I am simulating
i do not understand
Then no. What Collider instance would Unity return if you didn't make one?
Imagine I have a Box Collider on my object. I don't want the component to be attached to any GameObject but want others to detect Collider in the place where the Collider component is supposed to be.
for what purpose
The reason for why I want it is because I have many colliders I have to move by setting their position and it results in monstrous processing from Physics engine sometimes taking up to 11ms for single fixed update
The methods I see in profiler at this moment are Physics.SyncColliderTransform and Physics.SyncRigidbodyTransform
unity doesn't do that work for no reason
it does that so that the physics system can work in the first place
Are they static/kinematic colliders, or do they have a dynamic rigidbody?
I do not know how to tell if a collider is kinematic but I suppose it became a little better after I added Rigidbody to them
And they are triggers if it matters
You could try disabling Auto Sync Transforms in Physics settings and manually call Physics.SyncTransforms when you're done moving the objects.
It will also still always sync before FixedUpdate. But with this setting off, it won't sync every time a transform is changed.
It will always be called before FixedUpdate. Whether you need to call it more frequently than that would depend on if the objects are moved after/during the FixedUpdate and physics queries try to access them after that.
Or if you're okay with 1 frame delay, then you can just let the FixedUpdate sync handle it.
Seems like checked Auto Sync Transform provides the best performance...
It's disabled by default in modern projects for the opposite reason. Your single sync procedure might be shorter now, but you might be triggering it a lot more frequently depending on what you do.
I'm looking to understand which approach gives me more precision when measuring time. I want the timing to be as precise as possible. Say for example, I want the image to switch at precisely 1.5 seconds. Should I use update method (or fixed update or other variations). Should I use a coroutine?
My target application is WebGL and I'm assuming it's going to be accessible to a variety of OS and browsers with different hardware configuration. So I want to ensure that 1.5 seconds in the application is precise across these systems.
your precision is going to be limited by the fact that Unity (and basically all interactive computer programs) are frame - based.
The chance of a frame being rendered exactly at the 1.5 second mark is exactly 0.
The best you can do is draw on the next frame which immediately follows the 1.5 seconds.
If you want something else to happen at some precise time after that 1.5 seconds, then you make sure after drawing the thing, you don't discard the intra-frame error in timing
so for example, a quite accurate 1.5 second timer:
float timer;
float interval = 1.5f;
void Update() {
timer += Time.deltaTime;
while (timer >= interval) {
timer -= interval; // note we subtract interval rather than setting to 0.
// setting to 0 would discard the error time
DoSomething();
}
}```
Thank you! The application that I'm prototyping isn't a game but more like a UI application. What application should I be using if I'm concerned about precision of time measurement?
there is no digital computer-based application that will not have this limitation without some custom hardware.
what exactly is the use case?
What are you making? We can give better advice if we know the use case.
I was under the impression that frame-based approaches are better because the in-application timings are better when we factor frames vs. just measure system time.
I'm trying to make a reaction test. E.g., you know how there are applications that people use to improve their reaction speed?
So imagine a simple UI application where the users react to a stimulus before it's gone.
In that case just vsync your game/crank up FPS to the highest.
It doesn't matter how precise your timing is, user's monitor is still refreshing at a set rate.
You can't display anything until the monitor refreshes.
Ok so really the important thing here is input responsiveness. Rendering actually shouldn't matter as much. I.e. you want to be able to read input as quickly as possible rather than relying on the rendered framerate. in that case you may want to look into this:
The new input system has raw input time reported by hardware as well.
But the catch is that this application will be for a variety of hardware/software configuration. So I thought a frame-based approach would work better because let's say a browser is laggy. Then I don't want system time because that's not correct measurement but in-application time.
You would judge user's reaction time based on hardware input time, not frame time.
Thank you! This is great!
actually you mentioned it's WebGL - I don't know if that package will work in webgl
only windows-targetted applications
Not sure what's available in WebGL exactly
You may be limited in your precision here by what the browsers actually give you in terms of input exposure
It will be limited to browser time precision and no way around it.
If you interop with JS, you can use performance.now() which provides the highest precision browser allows you, but even that may still be limited (eg Firefox limits the resolution to prevent time fingerprinting to protect privacy)
True. But the in-application time is also a factor. Let's say the application starts measuring reaction time but it's not rendered on the screen. So the user will have a greater lag.
Thank you!
Any resource available to read more about it?
You simply use the frame time as the start time.
If what you are measuring is how long until user inputs after they see the frame, then that's exactly what you need.
float timer;
float interval = 1.5f;
void Update() {
timer += Time.deltaTime;
while (timer >= interval) {
timer -= interval; // note we subtract interval rather than setting to 0.
// setting to 0 would discard the error time
DoSomething();
}
}
Something like this then right?
Just user hardware input time - frame time.
Exactly. That's what I'm measuring.
Depending how these various input backends (from OS -> Browser) generate the input timestamp, I would start with that first before trying to create browser counters. Browsers generally avoid providing high precision timers anyway with recent CPU exploits.
Hi. I want to create a 3d array of voxels. Each will have a float value and it's position (whole numbers). I will have millions of them, if not billions. Many of them will have the same values, even whole numbers. How can I compress the data so it's using as little space as possible?
Thank you!
Thank you all!
The optimal compression technique will depend on the data itself, how the values are distributed, etc..
Probably the first thing you should look at is to not store the positions at all.
For example similar data structure can be a Minecraft world. Many copies of the same values, with positions as integers.
I thought about it, but then I'll need to compute these positions several times instead of once, which multiplied by millions can affect performance
Minecraft is essentially stored as chunks (flattened 3D arrays of block id) and you could just compress those with any off the shelf lossless compression algorithm
Not sure what you mean, if you are concerning about stored size rather than runtime size
but yeah important to think about storage format vs runtime data format
Then once you read it out of storage, you would compute their positions once and have it available as the exact same runtime representation.
especially since you will absolutely want to use a world streaming technique
Concerning about size, but if not storing size, I'll need to create these points and destroy ony by one multiple times. So I can say it's a tradeoff
I think you are missing the point
Positions are only omitted in storage, when reading it out from storage into memory, you can compute those positions once, and it will be exactly the same for your runtime.
There is no runtime penalty, if you are not changing runtime representation at all.
It can be as large as a few gigabytes, so either way I'll need to compress it somehow, with capability of using them at runtime or to optimize regenerating the points when I need them
You would stream it like suggested above
You would never have your entire world in memory, that simply does not scale.
You need to do world streaming like minecraft does. Minecraft doesn't load the whole world into memory at once.
Maybe you're right. My application would require the massive amount of points at the same time, but maybe I can access them sorting by height, so I could fit them into 2d array and move it along the height
I need to create some sort of gradient in a 3d space to be specific
If I had a similar objective I would probably separate default data and modified data. If the world is procedurally generated, then you can easily regenerate missing voxels using the same formula and seed.
Where I start the gradient at the bottom, so instead of populating the 3d array, I can slide 2d array and gradient points with it
The data never gets modified, that's the neat part. But I need to access 10% of the data at once and throw it away
Is generation of the data costly?
I need to generate data similarly to A*, starting from the bottom. So I'll generate the same points over and over if I don't store them
Well, just by not storing positions, you already shrink your data size on disk to 25% of what it was.
I'm thinking about some compute shader to speed it up, but I'm now only on designing the work flow, so I don't know how large structured buffers I will need
Right, it's a cube with a defined dimensions, with floats inside. I was thinking about storing float values and list of powitions that have these values. Will that be more efficient?
Highly dependent on your data, but I doubt so.
Ok, thanks for now. I'll think if I can do any workarounds ๐
If I was you, I would get rid of the positions, then just use any compression algorithm (gzip, whatever) and see what it ends up being.
If that's still not good enough, look at your data and think about how to transform it to create more repetition.
Eg if you transform:
1234 1238 1242 1246 1250 ...
Into:
1234 4 4 4 4 ...
It will compress extremely well by the compression algorithm you already chosen.
For most applications that's already good enough.
#archived-code-general for advice on how to debug. Here are some that you could take:
- Start small (3x3)
- Remove all obstacles
ok, thanks
@gentle hedgeIf you really want to get the most out of compression, it's generally going to be lossy. But that shouldn't really affect much if you do it right
quantize the float data into integers. You'll lose a few decimals of precision. Really shouldn't be too noticeable
after that, you can just pack the integers using variable width encoding. You can do all of this yourself. Avoid using things like gzip
If you store individual positions based on the relative chunk location, it will also compress a lot nicer.
yeah, gzip would work best if you had lots of repeating patterns, which is probably not the case here
I'm trying to solve a problem where a headless server build of my game has a 0,0 viewport (as it's headless), which means my camera bounds checks completely break on the server logic.
Has anyone had to solve this before? I'm thinking I need to create an object that emulates a camera's frustum where I can supply a fixed ratio (e.g. 16:9 most likely) for visibility checks.
Why would you make a camera bounds check on the server..?๐ค
server-authoritative off-screen player respawns
wat
HI everyone. I have a 911 emergency. I'm working on a final project for the semester and I'm trying to spawn clones with a transform position script inside them.
you'll need to say more about what you're doing
You could provide the necessary info from the client(like the screen resolution) if it can vary between clients or use a fixed value if it's the same for everyone. Then use it in your calculation.
That doesn't sound like a question or a description of an issue... Not to mention that it doesn't sound like something relevant to this channel.
is this a question?
Sorry let me find the words
hm. we're trying to err away from letting the client tell the server what's what as it's a little hack-prone, but that might make more sense to go about it from that side.
There's generally built-in engine solutions that deal with things like this
Well, the server can't just magically guess the clients hardware. Some things you've gotta provide.
But I'm also sure it's possible to emulate the geometric calculation a camera performs with a fixed ratio
You still haven't said what you're trying to achieve
Sure, if you have all the info needed.
that's the thing, I don't need the server to know the client's hardware. Even though we're supporting multiple resolutions, a fixed check at 16:9 would suffice for this issue
Then you should have all the required info on the server.
Yeah so that's what I was looking up, but that method still pulls those planes from the camera, which makes me think it is still deriving those plains ultimately from the viewport numbers
if the viewport is 0,0, what would those planes be?
No it doesn't. They use GeometryUtility.CalculateFrustumPlanes in the example, but you could calculate them manually.
there's no aspect ratio information and I can't see where to try injecting it
You'll need to look up how to calculate frustum planes.
that sounds the way. I guess that's platform agnostic and something I can look for
@vast shaleHere's the problem with what you're doing. The client is going to be predicting his position and orientation. If you're spawning things in/out depending on what the server players are "looking at" then the actual clients are going to see things teleporting and spawning in and out. The client and server "client" are seeing different things at different times.
There's also this overload:
public static Plane[] CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix);
You'd only need the "camera" transform for this one.
Maybe not. Confused with the transformation matrix.
in this game, all players see the same screen
that doesn't make any sense
if that's the case, that's on me for not fully explaining the nature of the game, the server-client architecture, and the reason I'm solving this. But trust me, I just need to do this manual calculation
I'm explaining to you how networking solutions work
it doesn't matter if they're viewing the same scene
unless this is being locally ran on the same machine, the clients are going to see things teleporting in and out, if I'm understanding what you're trying to do
we're two years into this project with a team of 50. We've had our netcode setup and essentially finished for a year. The entire game works perfectly. EXCEPT..... camera checks on our headless build.
Burt is correct though. If you do the check on the server just like that, there's a high chance your players would actually be able to see things spawning.
Even in server authoritative networking solutions, the client always has a small, but fair degree of authoritativeness
you're not understanding, but again that's on me. And I really appreciate the thought behind trying to correct my initial approach - it's totally fair to take that viewpoint, but it's just me not explaining the full situation properly.
the players are supposed to see the spawning.
Oh, then I guess we got it wrong.
They still might not see it then.
it's fine, haha. I really do appreciate the help. But yeah - players pop and teleport, other players see it, don't see it.. it's completely a non-issue and non-concern. The catchup off-screen respawn mechanic is completely surfaced on the front-end with full intention.
it's just when the logic runs headlessly, they respawn constantly obviously, as they are always "off screen".
the fllback is we just use a world-position difference, which again even that is passable, it's just a bit shitter and will be way more visible and obvious.
If you're fine with popping and teleporting, then why does it matter if they're within view of the frustrum?
Why not use a dot(player forward, dir to spawn point)?
Or even an angle
what matters is the essence of the respawn trigger. when the game is running in 4 player local, everyone has the same camera, if a player goes out of the camera, BAM, we fix it.
that's all it is, but with the architecture we have, we want that logic only running with state authority when in online sessions (dedicated server).
yes
that probably the worst way you couldve done this in a multiplayer setting
well, not falls off the map, goes out of view
why not just specify the bounds?
OK.. imagine this. we're making an olympcs track runner game. Four players.
one player runs REALLY FAST.. camera holds pace with leader.. one player is so slow they go off camera. What to do? well, instead of eliminating them, we'll put them back on the screen behind the player.
game design feelings aside, that's the entirety (simplified example) of the technical solution.
I don't work on rendering, but isn't each player's resolution going to absolutely screw this up?
there is a reason why its a good idea to separate logic from rendering ๐ค
if some one players the game on a portrait monitor, yes, it'll be bad for them. But I'm going to accept 16:9 ratio as a baseline and it is what it is. that will cover a majority of players.
bad solution
If the camera size of each player is the same regardless of their screens/hardware, you could just use a fixed bounding box and just adjust it's position based on the leading player.
why is it a bad solution
the server and all four clients have the same "active zone" of gameplay. All players see the same screen, same view, at all times.
I'm not tlaking about screwing with resolutions? at all?
I'm talking about a way to approximate a camera's field of view when the regular way of doing it is unavailable
Is it an orthographic camera?
no, if it were I'd set easily
there's dynamic camera logic for player-framing, so FOV is fluid, along with distance, and lerped movement and aiming.
And that is not controlled by the server?
that's simulated both sides
Well, if you need precision, you'll need to figure out a way to calculate frustum planes manually. Probably a googleable answer.
Yeah that's gonna be my approach
don't need full precision either, again this is a fully surfaced game mechanic, for soft rubberbanding. nothing about this execution has to be seamless or invisible to players.
thanks for your help
How can I enable a global database into Unity
OKAY... SO. I'm using Firebase with Unity and I'm trying to track in real time the position of IRL beacons to move some prefab objects that I'm spawning on the screen. FOR SOME REASON, the sensor values keep getting set to zero somewhere in the process, and I don't know why. I don't know how to find what I'm doing wrong. I come seeking advice from yee great Unity cabal! (gong noise)
seriously please help
Not sure if that question makes sense. You'd use a database in unity same as without unity if that's what you're asking.
Well, what steps did you take to debug the issue?
I guess I should ask which database should I use with Unity if I want different PCs to access the same one
Would Firebase be good for that
Yes. Firebase would work. Sounds like you're looking for a database on a cloud. There are many companies that provide such services, like google(firebase), amazon, microsoft, etc...
I think unity has some solution as well now.
stepping through with debugging, log debug statements, the works as far as I can tell
Well the database I want has to keep track of people's locations
latitude, longitude, etc.
What data you store in the database isn't really relevant. All of the solutions would probably work for that.
Well, at what point is the value reset?
Got it, thanks!
What are the "sensors"? Are they some outside(outside your unity project) devices/apps that set the values in the database?
as far as I can tell, I think it's when I'm constructing the prefabs. I have a beacon class and a driver class and a datamanger class, the datamanger class calls the beacon class and then is supposed to be assigning a beacon to new instance of the driver class, which prefabs a car?
So is the data to be set retrieved from the database and used to update the new prefab instance position?
The sensors are cellphones that my professor has that are tracking bluetooth beacons and then inputting values into a JSON file in the database, there are 4 values that it's populating that say the distance of the beacon from each of the sensors.
it's being set and retrieved in the beacon class and then being called in the Driver class which then passes it to a trilateration algorithm to track the position of the beacon in 2d space
Are these cellphones using some other app to update the database?
Are the database values only updated by the sensors?
Debug both the sensors data(specifically what they update the database with) as well as the data retrieved from the database in your game.
I don't have access to the console and I know the data is populated with different values at 1 point and then when I press play they all go to zero
What console?
And what does it have with pressing play? Is there non-runtime involved? Pressing play, reloads the domain and assembly, which would reset your app state in the editor. But if you're only reading the db values in unity, that shouldn't matter.
Really, there's not enough info to say anything specific.
This is my first time using Unity, C# both, and Firebase. I'm so lost.
Then maybe start with something simpler? We can't help you if you don't know what you're doing. Especially in this channel.
I would if I could but this project is due tomorrow and if I don't get it done I have to do an entire extra year of school.
How did you end up doing a project like that a day before deadline..?
Without having experience in unity, C# or databases.
No I spent a month on it then had to start over from scratch
Well, I'm not sure we can help you without you explaining your project structure and issue clearly.
damn that sucks
I was trying to do the entire thing with primitives the first time and that's just pure C# with lots of drawing calls. My code got so F'ed up that it was unreadable. I got permission to redo it in Unity but with only 3 days to do something that I have been working on for a month.
I have gotten WAY further using Unity than I did in a month of primitives. I really like Unity and if I could just get this one piece working and understand how it works, I could finish the project in a night.
To be fair Monday and Tuesday I coded and read tutorials 16 hours straight. My roommates actually had to check on me to make sure I was okay.
From what I've heard so far, the issue has nothing to do with unity. It instead has to do with reading and writing to a database. Did I misunderstand the issue?
It's reading from the database and parsing the data to clones. No writing is done to the database on my end.
I do in fact get the data but it seems to disappear when I instantiate the clones.
Ok, then you should be able to tell if the issue is in parsing by logging the values right after parsing.
I'm fairly certain that that is the issue but I don't know where the ball is being dropped in the process. From everything I have read, it should be working.
Then share the relevant code
Data Manager Class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using System;
//using Firebase.Extensions.TaskExtension;
public class DatabaseManager : MonoBehaviour
{
public GameObject CarPrefab;
public DatabaseReference Beaconreference;
public DatabaseReference ParkingMapreference;
public DatabaseReference Sensorsreference;
// Start is called before the first frame update
void Start()
{
Beaconreference = FirebaseDatabase.DefaultInstance.GetReference("Beacons");
ParkingMapreference = FirebaseDatabase.DefaultInstance.GetReference("ParkingMap");
Beaconreference.GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
// Do something with snapshot...
Debug.Log("Beacons: " + snapshot.ToString());
foreach (DataSnapshot child in snapshot.Child("data").Children)
{
Beacon beacon = (Beacon)ScriptableObject.CreateInstance(typeof(Beacon));
beacon.SetupBeacons(child.Reference);
beacon.d1 = Convert.ToDouble(child.Child("D1").Value);
beacon.d2 = Convert.ToDouble(child.Child("D2").Value);
beacon.d3 = Convert.ToDouble(child.Child("D3").Value);
beacon.d4 = Convert.ToDouble(child.Child("D4").Value);
GameObject vehicle = Instantiate(CarPrefab);
Driver driver = (Driver)vehicle.GetComponent(typeof(Driver));
driver.StartEngine(beacon);
Debug.Log("Driver: " + child.Child("D1").Value);
Debug.Log("Driver: " + driver.thisbeacon.d1);
Debug.Log("Driver: " + child.Child("D2").Value);
Debug.Log("Driver: " + driver.thisbeacon.d2);
Debug.Log("Driver: " + child.Child("D3").Value);
Debug.Log("Driver: " + driver.thisbeacon.d3);
Debug.Log("Driver: " + child.Child("D4").Value);
Debug.Log("Driver: " + driver.thisbeacon.d4);
}
}
});
ParkingMapreference.GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
// Do something with snapshot...
Debug.Log("ParkingMap: " + snapshot.ToString());
}
});
}
// Update is called once per frame
void Update()
{
}
}
Sensors Class
using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using UnityEngine;
using Firebase;
using Firebase.Extensions;
using System;
public class Sensors : MonoBehaviour
{
public static Sensors instance;
// Start is called before the first frame update
public static Point[] data = new Point[4];
public static int total = 4;
public DatabaseReference Sensorsreference;
// Start is called before the first frame update
void Start()
{
Sensorsreference = FirebaseDatabase.DefaultInstance.GetReference("Sensors");
int i = 0;
Sensorsreference.GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
// Do something with snapshot...
foreach (DataSnapshot child in snapshot.Child("data").Children)
{
data[i].X = Convert.ToInt32(child.Child("position").Child("x").Value);
data[i].Y = Convert.ToInt32(child.Child("position").Child("y").Value);
i++;
}
Debug.Log("Sensors: " + snapshot.ToString());
}
});
}
}
Beacons Class
using Firebase.Database;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Beacon : ScriptableObject
{
public double d1;
public double d2;
public double d3;
public double d4;
public DatabaseReference beacons;
// Start is called before the first frame update
void Start()
{
}
public void SetupBeacons(DatabaseReference d)
{
beacons = d;
//beacons.ValueChanged += HandleValueChanged;
beacons.Child("D1").ValueChanged += HandleValueChangedD1;
beacons.Child("D2").ValueChanged += HandleValueChangedD2;
beacons.Child("D3").ValueChanged += HandleValueChangedD3;
beacons.Child("D4").ValueChanged += HandleValueChangedD4;
}
void HandleValueChangedD1(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError != null)
{
Debug.LogError(args.DatabaseError.Message);
return;
}
// Do something with the data in args.Snapshot
d1 = Convert.ToDouble(args.Snapshot.Value);
}
void HandleValueChangedD2(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError != null)
{
Debug.LogError(args.DatabaseError.Message);
return;
}
// Do something with the data in args.Snapshot
d2 = Convert.ToDouble(args.Snapshot.Value);
}
void HandleValueChangedD3(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError != null)
{
Debug.LogError(args.DatabaseError.Message);
return;
}
// Do something with the data in args.Snapshot
d3 = Convert.ToDouble(args.Snapshot.Value);
}
void HandleValueChangedD4(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError != null)
{
Debug.LogError(args.DatabaseError.Message);
return;
}
// Do something with the data in args.Snapshot
d4 = Convert.ToDouble(args.Snapshot.Value);
}
// Update is called once per frame
void Update()
{
}
}
Driver Class
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Driver : MonoBehaviour
{
public Beacon thisbeacon;
public void StartEngine(Beacon b)
{
thisbeacon = b;
}
void Start()
{
thisbeacon = (Beacon)ScriptableObject.CreateInstance(typeof(Beacon));
}
public static (double, double) TrackCar(double x1, double y1, double r1, double x2, double y2, double r2, double x3, double y3, double r3)
{
double A = 2 * x2 - 2 * x1;
double B = 2 * y2 - 2 * y1;
double C = Math.Pow(r1, 2) - Math.Pow(r2, 2) - Math.Pow(x1, 2) + Math.Pow(x2, 2) - Math.Pow(y1, 2) + Math.Pow(y2, 2);
double D = 2 * x3 - 2 * x2;
double E = 2 * y3 - 2 * y2;
double F = Math.Pow(r2, 2) - Math.Pow(r3, 2) - Math.Pow(x2, 2) + Math.Pow(x3, 2) - Math.Pow(y2, 2) + Math.Pow(y3, 2);
double x = ((C * E) - (F * B)) / ((E * A) - (B * D));
double y = ((C * D) - (A * F)) / ((B * D) - (A * E));
return (x, y);
}
// Update is called once per frame
void Update()
{
double x, y;
(x,y)=TrackCar(Sensors.data[0].X, Sensors.data[0].Y, thisbeacon.d1, Sensors.data[1].X, Sensors.data[1].Y, thisbeacon.d2, Sensors.data[2].X, Sensors.data[2].Y, thisbeacon.d3);
transform.position.Set(Convert.ToSingle(x), Convert.ToSingle(y), 0);
}
}
There's also a parking spaces class but I'm not doing anything with that yet.
Ok,so what exactly is being reset?
in the driver class r1, r2, & r3, should all have data in them. In the other classes they're called D1, D2, & D3.
There's also a D4 but I'm not doing anything with it because it's easier to do trilateration with 3 points instead of 4
So basically, thisbeacon.d1/2/3?
yes
I see that you create a new instance of Beacon and assign it to thisBeacon. Wouldn't that set default values? Do you set the d1 values somewhere after that?
Oh, nvm. You shared the Beacon script too.
The d values seem to only be updated when the value in the db is changed. That would mean that initially they're 0.
You probably need to update these values when you create a new instance of a Beacon.
In my DataManager class, when I create the beacons, aren't I setting the values there?
The one you create in DataManager, yes. But you're not using it in your Driver class. You create a new instance there.
Ah, I see you're passing it in StartEngine.
Well, is it being called before or after Driver.Start?
Because if Start is called after that, you're referencing a new instance instead of the one passed to it.
Add logs in your Start and StartEngine methods and see the order of execution
You're amazing. I commented out the line in Start and now it works.
or at least the values aren't disappearing
Thank you SO much
Hello! I'm working on a script that overrides the textures of a specific terrain layer at runtime. While the diffuse and normals are stored in their own Texture2DArray's, the Height/Smoothness/AO are stored within the green channel of the diffuse/normal textures (not sure how that works). However, those textures can also be accessed through a struct that's found within the subshader of the shader I'm using for this (MicroSplat). Is there a way to access the struct through code to override these textures?
My script:
{
StartCoroutine(ReplaceTexture());
}
IEnumerator ReplaceTexture()
{
yield return new WaitForSeconds(1);
Debug.Log("10 seconds waited");
myTerrain.materialType = Terrain.MaterialType.Custom;
Material terrainMat = myTerrain.materialTemplate;
Shader shader = terrainMat.shader;
Texture2DArray diffuseArray = terrainMat.GetTexture("_Diffuse") as Texture2DArray;
Texture2DArray normalArray = terrainMat.GetTexture("_NormalSAO") as Texture2DArray;
Debug.Log("Array depths:" + diffuseArray.depth + " " + normalArray.depth);
Texture2DArray newDifArray = new Texture2DArray(diffuseArray.width, diffuseArray.height, diffuseArray.depth, TextureFormat.DXT1, 11, false);
Texture2DArray newNormArray = new Texture2DArray(normalArray.width, normalArray.height, normalArray.depth, TextureFormat.DXT5, 11, false);
for (int x = 0; x < diffuseArray.depth; x++)
{
for (int y = 0; y < diffuseArray.mipmapCount; y++)
{
if (x == 1)
{
Graphics.CopyTexture(diffuse, 0, y, newDifArray, x, y);
Graphics.CopyTexture(normal, 0, y, newNormArray, x, y);
Debug.Log("Custom layer replaced");
}
else
{
Graphics.CopyTexture(diffuseArray, x, y, newDifArray, x, y);
Graphics.CopyTexture(normalArray, x, y, newNormArray, x, y);
Debug.Log("Texture copied");
}
}
}
terrainMat.SetTexture("_Diffuse", diffuseArray);
terrainMat.SetTexture("_NormalSAO", newNormArray);
Debug.Log("Textures set");
}
}```
hi , i'm encountering this error with thundra and beedriver during build process ```[225/227 88s] GenerateNativePluginsForAssemblies Library/Bee/artifacts/WinPlayerBuildProgram/AsyncPluginsFromLinker
CommandLine
GenerateNativePluginsForAssemblies
ExitCode
-1
Output
BeeDriver connection terminated
Killed
*** Tundra build interrupted (88.58 seconds - 0:01:28), 225 items updated, 224 evaluated
ERROR: Job failed: exit code 1``` I have no glue where too look , any ideas?
Contact the Thundra dev and inform them that your application terminated with an exit code of -1 from the Command Line GenerateNativePluginsForAssemblies in AsyncPluginsFromLinker.
I'm assuming it's this: https://github.com/thundra-io
someone help me to make a character jump because in my code when it jumps it doesn't come back down
Hi. How can I detect if a point is inside 3d mesh? I don't want to use colliders, because I don't want to be dependent of Unity Physics and my mesh can have way more triangles than max collider triangles count. I saw some implementation of a nice algorithm, but it's for 2d:
http://www.lighthouse3d.com/tutorials/maths/ray-triangle-intersection/
I thought about something that checks if some triangle crosses both X and Y coordinates of that point, then discards every other triangles. Then somehow if these triangles have a point inside with coordinates X and Y of that first point
You probably need to add some sort of gravity, either via Rigidbody component or your own script.
I give such a value to my NativeArray in FixedUpdate but when I am trying to read the NativeArray in LateUpdate it appears as already deallocated, any ideas why?
_foodPositionsNative = new NativeArray<Vector3>(foodPositions, Allocator.Persistent);```
FixedUpdate and LateUpdate are being called independently. Perhaps your LateUpdate happened before FixedUpdate. Have you checked if the order is right?
I now moved disposing to the point right before they are created, thanks
You can check how many times a line pass through a triangle.
Hey everyone,
I'm currently using a singleton pattern, that the managers are created at run-time when they are needed, so it isn't just sitting there in the scene.
I'm loading the UI prefabs from resources since the singleton is not scene-dependent and whatever the scene the player is on, the manager keeps working. I've seen this method in a post, and I found it interesting, so I'm implementing it in my current project.
Though I'm feeling a little weird about this and I feel that there is a better way to do it. Since we load the UI and our singleton is not on screen until run-time, I can't just reference the UI elements on the inspector, instead, I need to find everything on my prefab for just then manipulate them according to my needs, which takes time.
My question is if this approach is bad and if it is, is there a better way to do it?
Hello, I am trying to Implement a custom update to unity but I am having 2 problems, when I move the slider for target fps on the UI for some reason the gameplay update seems to go faster, and then I think I have a problem with delta times for smoothing movement
https://gdl.space/unegovoqoy.cs
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
from where are you referencing ui elements in inspector?
You can create a script that is supposed to manage the UI prefab and store a reference to that script instead of GameObject*. Then you could just call a method from that script and initialize it inside the prefab instance.
*note that references to prefab components sometimes can break on asset import error ๐คทโโ๏ธ
Can anyone try to help me with this issue or talk through it?
any suggestion how to distribute prefabs randomly across rect?
I can't come up with an algorithm
I need to fill whole area
Vector2 coord = new Vector2(Random.Range(rect.xMin, rect.xMax), Random.Range(rect.yMin, rect.yMax));
I need distribution
looks like a random distribution to me
but this will be tiled
this will do it
this will also generate positions where two objects collide with each other
you didn't say that was an issue
look up Poisson Disc sampling