#archived-code-general
1 messages · Page 152 of 1
you can use a single buffer
?
oh yeah, that prolly would be much more performant
Ill keep that in mind if this ends up needing the performance boost
Hmm...I want to use addforce to move the player, but I ran into a bit of a problem. I want to make it so that there is a maximum amount of force a player can add using WASD input, but if you are airborne, forces like jumping, explosions, etc can make the player move even faster. I want their airborne speed to be essentially limiteless. I tried setting a maximum velocity, but I quickly realized that this would cause the airborne velocity to follow the same rules as the running/strafing velocity. How can I set a max input velocity or acceleration to my rigidbody?
as an idea, get a normalised vector for the player input and dot it with the current velocity - if the result is greater than the maximum magnitude of velocity you want the player to have direct control of, then discard the input
hello, can someone help me understand what im missing in regards to saving:
I have a mobile game that saves a json file to the application.persistentDataPath and this works fine in the editor, however building and running the game onto my android, I find that I cannot find the file
The first image shows the file in my local machine when saving on my local pc
Setting up a log in the saving process, building and running the game on my phone, and viewing said log in LogCat shows the directory of the that file
2023/07/18 20:20:57.977 3978 4040 Info Unity Saving settings to: /storage/emulated/0/Android/data/com.DefaultCompany.marblegame/files/settings.json
I navigate to that file and find nothing (second image)
I know for a fact that it exists because everything I open the game, the save file is loaded and my settings are applied correctly
What might I be missing here? I want to view the file so I can debug an issue
I have windows file explorer set to view hidden files btw
How are you sure that the file was actually written?
also that directory doesn't look quite the same
for example, I have a slider UI element that has its value set when that file is loading as well as saved when the app closes it. it works fine. Ill set more logs up.
from what I understand /storage/emulated/0/ is ignored
I could be wrong about the second part but I do not see the storage directory when navigating my phone in file explorer
logging when you write the file would be a good start - as well as logging the file path as that happens
also showing your code for writing the file would be good
Saving
public void SaveSettings()
{
SettingsSaveData.musicVolume = MusicVolume;
SettingsSaveData.sfxVolume = SFXVolume;
SettingsSaveData.vibrationState = VibrationState;
string jsonData = JsonConvert.SerializeObject(SettingsSaveData);
File.WriteAllText(_settingsFP, jsonData);
// This is the log in the log entry that you suggested to implement
Debug.Log($"Saving settings to: {_settingsFP}");
}
Loading
public void LoadSettings()
{
if (File.Exists(_settingsFP))
{
// If the save file exists then read it
string jsonData = File.ReadAllText(_settingsFP);
SettingsSaveData = JsonConvert.DeserializeObject<SettingsSave>(jsonData);
Debug.Log($"Loading settings from: {_gameStateFP}");
if (SettingsSaveData == null)
{
Debug.Log($"File not found, creating new object");
SettingsSaveData = new SettingsSave();
}
return;
}
// Return a new score data object if no save file is found
SettingsSaveData = new SettingsSave();
}
I got this log when rebuilidng with the save log
2023/07/18 20:48:53.237 16704 16727 Info Unity Saving settings to: /storage/emulated/0/Android/data/com.DefaultCompany.marblegame/files/settings.json
Save file content:
{"musicVolume":0.0,"sfxVolume":0.389136523,"vibrationState":false}
should work
my thoughts exactly
HI, teams, when tried to add an example script, I met an error [No MonoBehaviour scripts in the file], but the file name is already same as class name. What should I do to avoid this?
Here's my code and file name, editor version is 2023.1.3f1c1.
ExampleClass.cs
// Initializes the target variable.
// target is private and thus not editable in the Inspector
// The ExampleClass starts with Awake. The GameObject class has activeSelf
// set to false. When activeSelf is set to true the Start() and Update()
// functions will be called causing the ExampleClass to run.
// Note that ExampleClass (Script) in the Inspector is turned off. It
// needs to be ticked to make script call Start.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
private float update;
void Awake()
{
Debug.Log("Awake");
update = 0.0f;
}
IEnumerator Start()
{
Debug.Log("Start1");
yield return new WaitForSeconds(2.5f);
Debug.Log("Start2");
}
void Update()
{
update += Time.deltaTime;
if (update > 1.0f)
{
update = 0.0f;
Debug.Log("Update");
}
}
}
ill keep digging, im sure its something small
reconnecting my phone and trying again worked
How can I check in a coroutine while something is true keep looping and if it is false then execute the code underneath?
yeah, but you'll want to yield inside the loop, a yield return null if you just want to wait until the next frame to check the condition again
alternatively, if you don't plan to have any other code in the loop you can yield a WaitUntil
I got it working! But just to understand it better how can I transform that arrow function into a normal function?
WaitUntil takes a parameterless Func that returns bool so you can just use a method that returns a bool. or keep the lamda expression, either one works
I didnt know about WaitUntil 🧠 🔫 that's handy
Okay, thanks
I just tested my code and the coroutine works but there is a minor problem
The coroutine runs before the camBrain.isBlending bool is first set to true
So it instantly runs the code after the WaitUntil
when are you starting the coroutine?
How can I check if a button is being held down and if a button is not being held down anymore through a script where it references the buttons? I can’t just use the onclick() trigger on the button it self because I need this to work with multiple instantiated copies of the player.
On update inside a function when the player presses a key
is this before or after you start whatever transition/blend for the cinemachine brain?
After
I incremented the priority of the camera and then started the coroutine
And I made the code only run once with a bool for it to not repeat endlessly
So right after the player presses the key there is a bool that stops the code from running again so it all only runs once
ah, in that case the actual update of the vcams is probably happening later in the frame. you could try a 1 frame delay at the beginning of the coroutine with yield return null; to see if that gets it working
Oh, so I could use yield return null and then yield return new WaitUntil() in the same coroutine?
yes, you can yield as many times as you'd like in your coroutine
Wow, thanks xd
actually you may want a WaitForEndOfFrame instead of null, but just try it with yield return null first
Then I guess it could also work by using first yield return new waitforseconds(delay), right?
sure, if you want to wait for a number of seconds instead of for waiting until specific parts of the update cycle
Boxfriend, do you mind trying to help with my issue after you’re done helping geeksand?
if i knew the answer i would have already provided it
Ok, thanks
Thanks 🙂
Quick question, how do you change the shadow quality of individual lights at runtime? I don't want to change the shadow quality globally, only for individual lights.
I learned about Light.shadowResolution, which seem to be exactly what I'm looking for, but the documentation doesn't have any examples of how to actually use this.
Does anyone have an idea on how to do this? Thanks (I'm using the built in render pipeline)
Thoughts on setting up a health system like this? Basically I was thinking this way avoids the need of getting the component on the target game object directly in a collision event/etc to apply damage, and instead you can just fire an event with the collider.gameObject, or w/e and if it has a health script, great, if not oh well.
i guess a downside is that the FireApplyDamage has to know which game object has the script attached to it to apply properly so it would be awkward to add as a nested child
Imagine you have thousands of objects with health. Each of them would get the method triggered and make a reference comparison.
Not to mention that it's plainly confusing implementation. It implies that Health is some kind of global object or concept.
Getting a damageable component on the go would be way better. Getting components on a gameObject is not that expensive, considering most of them have less than 10 components. If you have the component reference you would be able to do other stuff and make specific checks on it as well. For example, if you only want to apply damage to enemies, you could get the character component and check it's "team" or "faction" before applying damage to it.
if a script is disabled, afaik you can still get reference to it, as well as call functions on it, maybe im mistaken? This was also an attempt at basically making the script a no-op in the case its already been disabled
i mean i suppose i could early out, in those cases
I don't see how that argument is relevant to anything I've said.
You can make an enabled check all the same.
fair enough
Please read my question carefully.
A developer presses play button in the editor when the scene is playing. I want to show a dialogue box with yes/no button.If No button is pressed, it should do nothing. isPlaying = true freezes the game.
EditorApplication.playModeStateChanged += OnplayModeStateChanged;
private static void OnplayModeStateChanged(PlayModeStateChange state)
{
if (_state == PlayModeStateChange.ExitingPlayMode && Application.isPlaying)
{
if(EditorUtility.DisplayDialog(DialogTitle, DialogMessage, "Yes", "No")){}
else{}
}
}
}
isPlaying = true is the problem.
so you want to abort the mode change? if you're checking for exiting play mode, you're probably too late. Might be smarter to try and target the play button itself
I did not get
Suppose a level designer in play mode is working on a scene and suddenly press play button before saving it. I want to prevent it
why not just save the scene when the play button is pressed instead of showing a dialog?
what's the best way to get this difference assuming that white square is gameObject and I have RaycastHit2D info about red object?
note: player should be translated to that red square's position
what do you mean by the difference? the gap between?
exactly
i suggest using distance - collider.bounds
yes, should it look like this?
(2f - red.size.y - white.size.y) * .5f * dir.y
where 1f is 1 unit in world space
and 1f - red.size is diff between 1 unit and scale (don't mention prefab's initial scale)
something like this, it should be like take the AB vector, then you can use this vector to get distance and direction from one another. Then you can take the half collider bounds and multiply for the direction, then subtract from the original vector and get the distance of that one. repeat for as many objects as you have! i don't know if it's clear
not that clear actually.
Yes, it is a solution but maybe I do not want to save it always in exiting play mode
ok ill make a drawing for you in paint
actually this is working assuming that object is in center unit. so if it's gap between unit's max y and unit's min y is the same
then is works @lusty gull
if gameObject is in the center of unit
I see, so it's transform.position.y += A.halfBound + B.halfBounds + x
(I know that transform.position cannot be set like this)

halfbounds in my calculation is a float. If you need the direction information, you can use:
A + AB.normalized * (AB.magnitude - HalfboundsA - HalfboundsB)
will this work if gameObject isn't in the center of unit?
if it's position isn't inted (int)?
no. if you need dynamics not based on transform, i suggest looking into the Collider API
I see, thank you, I will try that!
the useful methods for you in this instance will be ClosestPoint and ClosestPointOnBounds
- Given a collision2d, can i get a color of the object i just collided with at the contact points?
about unity version control i have again same problem, one new project created by going to project settings -> unity project id, but unity version control using another projecct, how can i fix that? because i have changesets from one project pending in another project, a really big problem i made my self
yes, SpriteRenderer has color field
collision2D.transform.GetComponent<Renderer>.color;
- It has a texture. It's a tilemap renderer, and tiles do have various colors, they're not solid. So getting the renderer's color might give an approximation, but never the actual color. I mean it's ok if there's no other way around this, but i'd like to get the exact color of the collision spot
get color of its meterial probably
Hello is there anyway to make a triggered 2D collider reload on everytime i press fire1 button? i tried enabling and disabling the collider but it doesnt count any collisions with an object with collider
yeah
retrigger it
It should be possible to get the tile and it's texture and sample it somehow, but it's not simple.
hmmmm sounds like a good idea gotta try it thanks
wait, do you mean OnTriggerEnter2D method?
oh, collider
yeah
method?
I use OnTriggerEnter2D method
yes, you have to retrigger it manually
is there any way to do that in code? since i cant find any method or either a value to modify
yes, there is, hold on
tyty
aight
Physics2D.IgnoreCollision(triggerCollider, otherCollider, true);
Physics.Simulate(Time.fixedDeltaTime);
yield return null;
ah cool thanks
this should work
we ignore collision for 1 udpate, then simulate physics and retrigger OnTriggerEnter2D this way
the otherCollider is now the problem since i do not know who can it be.
you can also use Physics.IgnoreLayerCollision
tyty
Hey, anyone seeing anything wrong here? My player's not moving at all..
https://pastebin.com/B1Ahddrb
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
damn that makes the character to fell off
yes, you have to work with layers
you have to ignore specific layer e.g. Enemy
not all layers
also you can find collider by tag
or name
there are so many possibilities to do it
is onMovementInput method even called?
also currentMovement is too small
but it may be enough
Why do you even need to do something like that? It sounds like you're approaching the problem from a wrong angle.
im trying to create my own melee combat system for the game
but it seems i found an easier solution
That doesn't answer my question.
its called automatically by unity because of the started, canceled and performed.
But that's basically what you've asked
No, I didn't ask what you're implementing, but why you do it the way you do.
that was the only solution i found atleast by my own
Maybe explain what exactly you're trying to do? Detect when a sword is overlapping with the enemy or something?
fixed it, needed to add a speed variable
yes, it was sure too small
well i believe i fixed it* looks fine for now lol
aight.
I made a box collider 2D and made it with the scale of the swords' range.
i was planning if i could re enable the collider on attack and detect the new collisions.
also you probably don't wanna enable and disable new Input System like that
private void OnEnable()
{
playerInput.Movement.Move.started += onMovementInput;
playerInput.Movement.Move.canceled += onMovementInput;
playerInput.Movement.Move.performed += onMovementInput;
}
private void OnDisable()
{
playerInput.Movement.Move.started -= onMovementInput;
playerInput.Movement.Move.canceled -= onMovementInput;
playerInput.Movement.Move.performed -= onMovementInput;
}
Thanks!
don't see any reason to do it in 2 actions
just in start probably
it's just 1 script, so it doesn't make sense
also we write scripts from capital letter
Why would you need to reenable it?
to detect new collisions ig
Why not keep it enabled all the time?
it'd be looping on OnCollisionEnter2D or might only fire that event once
do you know OnCollisionStay2D?
The first is solvable with layers. Only make it collide with the enemy layer.
What's the problem with it firing only once per collision?
oh yes
do it yourself, as I have mentioned before
i want it to fire that event everytime the attack button is being pressed and the collision happens
You could cache the colliding objects and apply your logic to these objects only when you press the button. What's the problem?
it seems you're right gotta try it thanks
guys anybody knows if it's possible to use [BurstCompile] on extention methods?
I believe so.
How to make gameObject not be affected by Rigidbody2D at all, without making is static or kinematic (in order to trigger OnCollisionEnter2D)?
Does the thing you are colliding with have a rigidbody attached?
Iirc you need atlast one of the two to have a rigidbody
If yes, then you can just remove the rigidbody from your gameobject
Why do you need the collision?
to see when my player has collided with another collision and stop the game
Then the other collision could have a rigid body right?

it's moved by tranform.Translate
😭😭 it shouldn't have rigidbody, because it's behaviour will be broken then 😭😭
RigidBody.MovePosition
maybe I should move my player with it?
it's just updated after next physics simulation step
also when my player has rigidbody it's behaviour seems to be quite weird.
it doesn't seem nice
I just cannot move as usually
Looks like there's a collider on your playing field
And it's pushing it out of the field as soon as it starts
but it has different z position
Why are doing this weird 2d 3d mix man
what do you mean?
Not an expert on this but if you click 2d as a template when creating your project you shouldn't be getting stuff like this right
no
Also, try using a tilemap!
it should
why should I?
There's probably someone else on YouTube that can explain that significantly better than I do, but lets just say that it isn't required but it can simplify everything
Hello, I have an issue in my 2D game. I implemented a ledge grab which works with 2 collisions : one to detect the ledge to grab, and another one which verify that there is no "Ledge" above (so the player will grab the ledge at it's top). When I jump it's working pretty well, however if my character is too fast (-20 y velocity is the max), the box starts bugging and will sometimes detect the ledge and sometimes not. Does someone know how to fix this ? https://streamable.com/wfhc7k
Although not ideal, you can raycast from your previous position to find these kinds of colliders
Or up the fixedupdate rate
But I am pretty sure this is just a problem with any fast moving object
ok I'll try thanks !
You can also make your colliders larger
Btw double check this somewhere, maybe in #⚛️┃physics
ok I asked and I will see if there is a easier way to fix it ...
hello, any way to implement smth like OnCollisionEnter?
I don't mean functionality, I mean that my method should be "called" like it's
private void Foo(Vector3 smth)
{
// and here is already all information about `smth`
}
it also doesn't seem to be overriden
ok, it's hard one, don't care about it
I have another question. Why do BoxCollider2Ds not collide?
Depends on your setup
there are 2 gameObjects with BoxCollider2D and they just not collide
their z position is the same
on?
That are simulated?
no
no rigidbodies
One of them needs to be a rigidbody for unity to do anything with them
I think you can also manually call the physics functions from the context of the collider
I see, it isn't just OnCollisionEnter
so I move my obstacle in Update
private void Update()
{
transform.Translate(GetDirection(direction) * speed * Time.deltaTime);
}
and I check for collision in LateUpdate in another script
private void LateUpdate()
{
if (CheckCollision(k_obstacleTag))
gameManager.EndGame();
}
But late update is a bit too late
it does execute just when colliders are on each other
any suggestions?
Wow, looks like I should not be using lists for this
You can allocate memory in advance by specifying the capacity
Yeah, I was able to do that for the vertices but I am now in a puzzle for the triangle data, since there are different submeshes
and I dont want to pre allocate 256 large capacity arrays for worst case
I do have a solution idea though
Whatever you do, you gonna want to allocate contiguous memory.
List is just a wrapper around an array.
My plan is to make one main array with some logic around it, i already know the max case in terms of triangle indices (just integers)
And the type is denoted by a byte
So I think I may count all the types before generating and partition the main array sorta
each partition being the size of the worst case for triangles
worst case meaning all sides of the voxel are rendered
Are you generating the voxel base on visibility ?
Yeah so the original data for voxels is simple byte array,
a 3x3x3 chunk would be 27 bytes.
When I am generating the mesh I check visibility of each voxel that isnt empty
The time is super inflated with the deep compiler open, usually its <10ms for worst case
which is a grid that looks like this
Did you try without checking visibility ?
I made this code for bullets to move towards the direction of player in 2D environment but they are moving upwards.
Because I am not sure what is the performance upgrade you gonna gain.
Performance upgrade is massive
You might be doing something wrong then
this is the worst case, every face is exposed
You should not have an issue rending this.
I dont, my question is just to see how people would suggest splitting up the submesh types without allocating garbage
Maybe because you're rotating them too
It works very well but I am just further optimizing, this is 3x3x5 chunks all of the worst case.
Uses <5% cpu at any time and <25% gpu and i have a 1050 ti
moving around and destroying them even
Then why are you still optimizing ?
Its gross seeing 0.6 MB being allocated every time a block is modified
Also, you could use two step algorithm, one that define the amount of memory needed and the other that do the actual thing.
Ah maybe I should do that beforehand and include it with the block data
during generation
Count of each block type
Now no rotation made it simpler now.
Isometric Hexagon Tactics Battlemap: __Grid __vs GameObjects
My goal is to create an isometric hexagon battlemap with units moving across those hexagons on their turns. The hexagons will need to be** re-colored** / highlighted on various circumstances:
- when unit is selected to display where they can move + when I hover mouse on those tiles;
- when skill is selected to display where it can be used + mouse hover;
- etc.
The question is, which should I use to generate those hexagons: GameObjects or Grid?
Grid does sound like the perfect choice, but I struggle to find viable ways to constantly change how tiles are displayed based on different rules (distance from character GameObjects, etc).
Meanwhile, if the hexagons are GameObjects I'll be able to change their Sprites based on game state changes, mouse hover events, etc
Start by trying out this: https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html
Thanks, on it!
One thing that concerns me with the tilemaps is the constant need to calculate Vector3 mouse position and compare it to the positions of tiles.
I will also need to store an additional array to store info on each tile properties (isPassable, Effects, etc).
Would you say it's not a big deal and it's not worth using GameObjects just for that?
It is not a big deal.
isn't that something you'd only need to do once per frame?
And only write in one place?
You can add data on tile map tile with https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles-Example.html
With mouse -- probably, yeah, you're right.
With tile properties -- each time something happens, I'd need to apply those changes both on Tilemap, as well as that other array that stores all the properties.
Say, I pressed my mouse button on a specific tile and now it needs to be on fire. I'll need to change both the Tilemap (for visuals), as well as the array (to apply effect properties).
And all of that by comparing world coordinates to tilemap and vice versa.
with proper separation of responsibilities that's really not a big deal though
Ohh, so I can actually store all the properties there, right on tiles!
Okay, that probably solves the issue I just described...
all that code would not be in one place
Beware, those are ScriptableTile meaning that they are share by all the tiles. It is not made for Runtime modification.
You are probably right. Maybe I'm just too used to GameObjects that have everything I need in one place.
Ahh, I see. Then a separate entity for properties that is.
If you want to add data to change at runtime, you gonna want to either:
1- Use GameObject on top of the Grid
2- Use Dictonnary or other data structure to add data
3- Create your own tilebase (And instantiate it): https://docs.unity3d.com/ScriptReference/Tilemaps.TileBase.html
You need to ask a proper question, first.
#854851968446365696 if you need to see how to do so
(1.) If I were to Instantiate GameObjects on top of the Grid, I think I could as well give them Sprites and simply use that, couldn't I?
Other than that, perfectly clear!
@leaden ice @steady moat
Thank you both, I have more than enough to research / experiment with for now! 🙂 ❤️
just understood I could ignore collision between them, then realised collider can just be trigger 🙄
stupid me 3 hours ago
also you can read this short tip
it explains everything you need in 2 words
Im trying to make a dynamic physic material that belongs to the instance its assigned to. Would I need to make a struct or set of variables to re construct the physic material each time its modified or is there a more straightforward way of doing this?
Ive tried using a custom editor to create and modify a physic material when the instance is validated, but these changes are not ever saved.
if you're creating a physic material in memory in the editor you will need to save it as an asset for it to be persisted
but can't you just modify the one you're using as needed?
Why create a new one
So probably I'd do something like this:
class PhysicsMaterialController : MonoBehaviour {
[SerializeField] Rigidbody _rigidbody;
PhysicsMaterial _material;
public void SetPhysicsSettings(float bounciness, float whatever, ...) {
if (_material == null) {
_material = (PhysicsMaterial) ScriptableObject.CreateInstance(typeof(PhysicsMaterial));
_rigidbody.physicsMaterial = _material;
}
_material.boucninesss = bounciness;
_material.whatever = whatever;
// ...
}
void OnDestroy() {
if (_material) Destroy(_material);
}
}
that kind of thing
Well Im creating a prefab of a collection of objects with joints and colliders to represent a wheel, and I figure it could be useful to have the ability to dynamically adjust the properties at runtime. To do that though I need a material instance for every wheel. I couldnt just modify a material asset because that would modify the base and all of the instances that use it.
Yeah, in this case you can do: var newMat = Instantiate(_originalMat);
Just make sure to destroy it when you're done with it
ok so - create the instance, assign it to the object, modify it as needed.
How is that mechanically different from constructing one with new()?
It registers the SO properly with the C++ side of Unity
I mainly ask in case the way theyre cleaned up is considerably different, because you mention I need to destroy it I would like to know where the heck it actually goes when its created. I thought the garbage collector would handle the one created with new().
UnityEngine.Object derrived objects all have a C++ half and a C# half
GC only handles the C# half
Destroy is needed for the C++ half
Ohh because c++ doesnt have automatic garbage collection
yes, not only that but even if it did - you need to tell it to drop all the references to the object somehow. You can assume the engine tracks these objects somewhere
If I managed to accidently not destroy the instance is that something I have to manually clean up or would that just require an engine relaunch
it would be a memory leak
which may or may not be a big deal
Pretty sure when the Editor or application terminates, the memory is freed.
^ this for sure
but if your game is long running and you do it a lot, it can build up
unity has only MonoBehavior, ScriptableObject and various other injection points, what unity does is it creates a backend Mono object, linked with the c# object, which you extend
Yeah I know this, I just want to make sure there im not accumulating junk while editing.
only way for it to know you want a new native object is through the api it provided
How do I hide this field in derived class?
[SerializeField] protected Direction direction;
Only way would be with a custom inspector
if you want it hidden in a derived class then derived class was probably the wrong design decision
ok, I see, thank you
I think I just shouldn't care about it
private
?
protected means classes that inherit from this can access it
private means they cant
yeah, I know, why do you say that?
or do you mean you dont want it to show up in the inspector?
I want to show it in inspector for all derived class except one
I just cannot override it
so yeah, I just don't care then
You wouldn't be able to inherit the data as private.
you want it to be a hard set immutable value for the exception class?
how long have you been typing it? 🤔
no, I want it to not be shown in inspector in derived class
I was typing something other - was that important?
then you probably need to branch your inheritence higher upstream
You would have to write custom a inspector for the class you don't want that field showing
no, just my curiosity, I didn't mean to hurt you
no need to overcomplicate it with weird hacky stuff, usually this just means you need to further subdivice your inheritence out to make a branch
yeah, I know, PraetorBlue has told me that
I agree though that you could have the field private and serialized in the child parent and expose a protected property for the inheriting class to have access to the member though.
yeah, I just need this field in all other derived classes
youd have to serialize every single one of the other children, could be unweildy
what does it mean?
No this just sounds like you need to further subdivice your tree
exactly
You need another abstract class
Whats the names of these things so we have common lexicon
how does it help me?
names of..?
these classes we are talking about
so instead of "the things" I can say what they actually are haha
I meant parent @pure cliff
ObstacleSpike : ObstacleController
ObstacleLog : ObstacleController
EnemyStraight : ObstacleController
ObstacleController : ObjectController
kk
and then whats the high level reason you dont want one obstacle to have the field exposed
like what makes it special
because ObstacleSpike doesn't have any direction
it's just spike
it cannot move like enemy
gotcha
No probs, so what you want is to rename ObstacleController to be like, DirectionalObstacleController or whatever
what. why.
and then you want like
ObjectController -> ObstacleController -> DirectionalObstacleController
I see, you want me to do one more class
And then your spike inherits from just ObstacleController and all the rest inherit from DirectionalObstacleController
nah, that's so strange to do one more class just to hide one field
Now actually, you can pretty much have all your logic in ObstacleController still so
99.99% of the time once you start doing this, you start seeing other things that can go between the classes
this was just your first roadbump that made it obvious that you needed 2 layers of fineness for defining your obstacles
yeah, that really does make sense, but I don't wanna do it just for one field, I just don't gonna use it
yeah, I gonna do that if I find other things
nothing wrong with making a second class that just has a shorthand on it
that then saves you writing the same 1 line of code on a bunch of other classes
I was also thing about doing
EnemyController : ObstacleController : ObjectContorller
yeah EnemyController could be a better name if thats the special logic for "has a direction"
yeah, but Log is Obstacle and is has a direction
I just haven't invented full logic of my game
that's why it's strange
yeah so I think you will have multiple layers of defining your classes, and thats super normal
yes, probably more of them in the future
I also typically subdivide my folders to match these various layers, and I just call it <Category><Type>Base in my folder tree
You need to decouple stuff from the base class if they aren't available in every inheriting class
that's true, I'm still thinking about it
what's that?
For example I very likely will soon have EnemyEntityBase abstract class and UIEntityBase in this folder structure
I see, I also like ordering everything correctly
Though I have largely circumvented that by instead using composition pattern + strategy pattern
so instead of logic being on the entities themselves, all they set is "what is my strategy" and paramets for it, and then I grab the matching strategy class for em, I effectively inject in what their AI is for how they behave
I see, you have said those classes are abstract?
any class I end with Base is an abstract one
I have never used abstract classes before actually 🤔
all an abstract class is, is blocking the ability to new() one up
yes, that might be useful sometimes
Like if you have abstract fruit class, and then apple : fruit, as a normal class it means you are allowed to new apple() but you arent allowed to just new fruit()
The band-aid solution would be ```cs
Class A
private something//Field can be serialized and exposed to the inspector but private
protected Something//Property exposed to inheritant
can property be serialized?
oh, wait
no
we don't need it
you're right
Exactly
yeah so you wouldnt even have Direction in ObjectController, and only DirectionalObjectController will have it show up
no, I just need ObjectContorller this way
The other option is do what I am doing:
Dont care what "Direction" stuff like a spike is, it can actually be allowed to face left/right/up, but it has zero impact
yesh, it has Direction.None
cause in the end what direction my sprites face is purely handled by the animator
I'm kinda perfectionist, you see
so I would just have the spike have the same sprite for every direction
yes, it will have
yeah then that honestly is fine
even though my "sprites" are solid colors now
even solid colors as sprites are better than if I draw them myself
it mostly depends on
- how expensive your directional logic is to be running on things that dont care about it
- How many of them there are
Like its possible breaking out the class to refactor the direction logic apart, may cause a significant or insignificant performance change
yeah, that's true
making lots of classes and inheriting from them may be quite confusing, but it's much less confusing than if you have 100 half-same classes with repeating behaviour and 5 times more redundant code
exactly yup
and like I said, usually once you break it out a bit, you quickly start finding other things that belong in that layer instead of the layer above or below naturally
as you expand the project and start wanting other features you quickly go "Oh wow thank god I broke this out earlier, cuz now I have the perfect spot for <other thing> to go!"
yeah, half of my code will probably be changed once I add new logic to my game
that's why first things that I have done were parent classes for obstacles and objects
Im currently bumping into this awkward process of dealing with how I want my architecture to work with "bubbling up" events, because I have designed my whole game engine to be a big tree of services that are the "source of truth", and the monobehavior game objects sit at the very bottom of the tree, and their only job is to be controlled by the parent services
Should probably focus on writing code once and not having to touch it again unless you're doing so for learning purposes.
but... stuff like click events and whatnot occur on those monobehaviors all the way at the bottom, and the stuff that cares about if the event happens are close to the top, so I gotta like, bubble it up
writing game engine sounds crazy
I think I will be doing it in my currect game
eh its just all the core logic for my game
but I like to keep all my code largely aggregated into 1 large stack of services with a single entry point at the very top, and everything cascades down from there
use event bus
I can access the event, it just kinda feels messy
I just dislike events but I cant be having my models acting like they are services
I know what an event bus is yes
Pipe<T> would be the modern C# class to use to make a simple one
the separate services/systems stack is common, but what you described seems like overly imperative approach that defeats the purpose of component model
Id still have to hand off a reference to the writer to said classes, Id need to figure out how to do that
can you link to Pipe<T>
channel seems to solve a different set of issues
Channel is what I would use for an event bus
I first generate a list of directions the green lines are the directions within the fov and the red ones are outside. The yellow line is the transform.forward and im trying to find the closest unobstructed direction forward in the fov area but for some reason it returns the closest unobstructed world forward transform. can someone help ?
async support (but not mandatory), and works fine for a pub/sub model
var eventChannel = Channel.CreateUnbounded<MyEvent>()
and then you have eventChannel.Reader and eventChannel.Writer which you can async or synch read/write off of respectively
and hand off the reader to the thing you push to, and then you can hand the writer off to everyone who has events to push onto the bus
its pretty much just a Queue but it has support for stuff like Streams and Async reading/writing which can be nice
can you show me a simple example of some ui mono raising some event and some system subscribing to that event?
i want to compare apis with mine
@pure cliff @dusk apex thank you both for help guys btw
yeah so I have
public class WaitButtonEntity : EntityBase
{
...
public event EventHandler OnClick;
public void Clicked()
{
if (Pausing)
return;
OnClick?.Invoke(this, null);
}
...
}
As an example of the monobehavior (EntityBase is a mono)
It has a button which hooks into the Clicked() method
Im not using a channel atm I just hook into it directly
I was just saying if I wanted to use a bus, Id use Channel<T> but I havent yet
My main issue with event bus is it restricts you to trying to figure out how to make all your events "sameish" so they can use the same bus, and that can cause antipatterns to arise
eventbus mostly makes sense when all your events really are gonna be sameish in some way so thats not a downside
i dont understand
That or you have to make a bus for each different type of event which sort of defeats the purpose
struct OnClickedSomeButton : IEvent{}
void Clicked()
{
EventBus<OnClickedSomeButton>.Raise();
}
this is my current
yes there is no shared channel/pipe
havent required it, yet
so right now I just hook into the event like this
public class InputService : IInputService
{
...
public InputService(IEntityService entityService)
{
EntityService.WaitBtn().OnClick += OnWaitBtn;
}
private void OnWaitBtn(object sender, EventArgs e) { ... }
...
}
Hi guys, i'm trying to make an object stacked when clicked to only take half of it, but when both conditions are met, nothing happens, can someone please help me?
sorry to interrupt btw
public class InputService : IInputService
{
EventBinding<OnClickedSomeButton> _onClickBind;
...
public InputService(IEntityService entityService)
{
_onClickBind = new EventBinding<OnClickedSomeButton>(OnWaitBtn);
}
private void OnWaitBtn(OnClickedSomeButton ev) { ... }
...
}
here
Im not sure what this is
ah kk
Hello, is it possible to set a GameObject to a specific size and not just scale?
What are you expecting to do? the scale is the size
Wait, I may be misunderstanding things, Im just new to unity. Does any two objects given the scale of (1,1,1) will be the same size?
no
The sizes of the Mesh may differ
you have to understand that "size" is an abstraction
an object "size" can mean different things, for example in most cases you mean visual bounds of the mesh
You could have a huge building and a small player
the object can have no mesh, but a collider, then the size will be the bounds of the collider
both being the scale 1,1,1
the object can have no bounds from renderers or colliders, so it wont have any size
Is there a way to make them the same?
what do you want to make same size, 2 meshes?
I need to make a GameObject change in size based on a given scale
2 meshes?
Yes? Sorry, I am not used to the terms in unity
What is the game object? Itll be easier to suggest something if we know more
The game object is a 2d sprite
so its a sprite
sprites also have bounds and size
what is the problem you are trying to solve?
ie i place one sprite next to another but they are displaying differently
show a screenshot
I need to change the size of the object so that it will be in matching sizes with a map
The size of the object may vary in sizes since it will be uploaded by the user
Nope, I want it to scale correctly with the map
The user will also give the scale in m(unit)
ok do you have consistent ppu across all sprites?
can the ppu be used as a basis for size?
I think no. The only thing the user know is the scale in meters. After that, the object should match the size with a map
how does user set the meters?
The user just knows what the size of the sprite is based on meters. Because it will be made with that on mind
But their sizes will not be uniform
The user will make a sketch outside the app and will upload it. It will then be overlayed on a real world map
ill rephrase
Thats why it needs to be correctly scaled to meters
what is the correlation between meters, and the sprite user makes
what exactly should user do to achieve a 2x2 meter sprite
For example, the user makes an image which should be 2m in length on real world. Of course it will not literally be a 2m image. What I need to do is to change its size to be 2m when overlayed on a real world map on the app. The user knows that it is 2m in size and will be able to input that on the app. But the problem is the images made may not be in uniform sizes. Like one may make a 500x500px for 2m irl size. Another one may make a 700x700px for 2m irl size
ok, so you have the size in provided by user, you have constructed the sprite at runtime with Sprite.Create()
which accepts ppu value
use some universal ppu across all sprites, for example 100
then simply scale the image by the factor of the meters the user provided using 100 pixels as one meter initially
so a 512*512 sprite will be ~5x5 meters
target is 2x2
the math will be something like
float scaleX = (ppu * targetMeters.x) / sprite.width;
Thank you so much! I can finally do it
The way you explain things is so easy to understand. Also sorry for not being very clear at asking questions
How can I set whether or not a particle system loops on runtime?
It's probably because your buttons are not anchored properly, so their detection area gets moved when the resolution changes.
Ask in #📲┃ui-ux as it's not a code issue.
Post the question as text for folks with limited data plans and slow networks.
Thank you, but how do amour them properly
What?
Love when one of my methods starts always returning true :(
Anchor? The #📲┃ui-ux channel has some links to tutorials on how to do it
K
Ah, misunderstood what you were trying to do - since this is a Editor script, you want to use EditorApplication.isPlaying instead, with your example:
if (state == PlayModeStateChange.ExitingPlayMode)
{
if (EditorUtility.DisplayDialog(DialogTitle, DialogMessage, "Yes", "No")) { } //do nothing, exit will happen automatically if "yes"
else { EditorApplication.isPlaying = true; } //prevents exit if "no"
}
Say what? You'd use the Unity Hub and Editor to open Unity projects.
GitHub is a code hosting platform for version control and collaboration. It lets you and others work together on projects from anywhere.
Relative to working together and from anywhere: you'd have the same versions synced using version control.
there's nothing special about a Unity project managed by git and any other unity project. You just open it like normal from the Unity Hub
Is there a preset or an easier way to set a RectTransforms anchors based on the size of the parent? I'm finding I do the following - and it seems like there should be a better way.
In the video, I show how I get a dialog box to resize properly based on the parent. First I do it without any anchoring, then I do it with the default anchoring, then I show how I get it to work correctly: I have to memorize the size of the parent (in this case, 1920x1080), then set the child to stretch, then manually set the left/right/top/bottom anchors to AnchorMinX = L/W, AnchorMaxX = 1-(R/W), AnchorMinY = B/H AnchorMaxY = T/H
I do this often so that all my elements size properly but it seems like this should be a default anchoring setup somehow? I'm thinking maybe I should/could write an inspector plugin for this? Or am I just doing something incredibly naive/wrong?
I don't really know what the math you're doing there is but the resulting values you're getting are just pretty intuitive percentages. E.g. 24% of the screen to 76% of the screen or whatever
could you not just think of it that way?
There are also additional options if you hold down SHIFT or ALT before clicking, when you open that menu @ 7 seconds of your video, I believe SHIFT lets you do essentially what your doing manually
Yeah, I'm just saying I have to do the above like... over and over and over when I nest components. If I do a nav bar that's 1920x100, then every button inside it that I want to be scaled properly has to do the above
I feel like there should be a preset? for what I'm doing that I'm not aware of
Or is this anchoring just part of y'alls layout process as well? Ie, figure out some reference resolution and manually lay every item out pixel by pixel..?
I defeinitely don't think about pixels
I think in terms of percentages usually
occasionally "pixels" when doing offsets at the top
e.g. like 10 units from the border or whatever
so there's no math - in your case I would have just written .24 and .76 directly
yeah the only problem with that (using "pixels" instead of percent) is then they break when different scales
ok, i could probably shift my brain into working like that
I always thought that "code rot" was the tendency of unmaintained code to fall out of date with libraries. But I've seen it used elsewhere in different context. How so you folks use it?
i could even make my reference resolution something like 10000x8000 (or whatever 16:9 is)
code that is old ("old" per changing scope/requirements)
Something like:
- Comments no longer accurately describing what the code does
- The original nicely designed architecture and abstractions getting polluted over time by small "fixes" and hacks
Or not even negatively connotated scope changes. IE, you've got a player object with a deepcopy:
public struct Player
{
public string Name;
public Player DeepCopy()
{
Player p = new()
{
Name = this.Name,
};
return p;
}
}
Then your designer says "we need age, too!" so you add public int Age and now your DeepCopy() is "rotten". Simplistic example, perhaps
Oh i forgot to metion the buttons still show in the build they just don't work
Help my Coroutine is stopping inside an if statement and I have no idea why. It is only in one particular condition in the coroutine, there are no errors and I am not deactivating the script in any way.
Anyone know why this might be and how to check what's wrong?
paste code
you would have to show the code. Can't help based on nothing
I know, have you fixed the anchoring?
Maybe you have another object that goes on top of the buttons when the size changes, because it's not anchored properly. And that's blocking the mouse clicks from reaching your buttons
The only things that will stop a coroutine are:
- Deactivating the GameObject it's running on
- Calling StopCoroutine or StopAllCoroutines
yield break- Destroying the GameObject it's running on
- an exception being thrown
@random oak
it only stops when reaching line 39
Debug.Log($"{player.PlayerName}...Got {card[0]}!");
That's a log statement, it can't stop there
it will only stop on yield statements
unless you get an exception
it doesn't reach line 80
line 80 is in the else
else won't run
since you're in the if
87 will run after 39
I watch a quick tutorial changed, but i might have done something wrong. Then it tryed it on a couple resolutions and it all still worked
is it not outside?
sorry line 89
it always reaches line 89 normally but doesn't when inside line 39
show your console window when this happens
(the whole window)
ok I will try, it only hits that if statement if the bot has no matching card and has to draw
Ok first off you have Collapse turned on in your console
you should turn it off
with Collapse on the logs will not always show in order
second - please show the full console window in these screenshots as it's important to see everything especially the top right and top margin
ahh didn't know sorry
See how ENDED ROUTINE has a (2) at the end?
That means that it happened twice
so it is indeed running when you expect
but due to the COllapse setting it is not showing again after the other log, it is merely being added there as a (2) @random oak
when you turn off Collapse it will show as expected
ok let me try again with no collapse, I have to restart editor cause unity flooded me with errors when I did
2022 shenanigans
yeah it's weird now is working after draw??
yeah it keeps working so far, idk so maybe some weird editor bug causing coroutine to act strange?
I'm so confused
It was working always
the logs were just obfuscated by the COllapse setting
at least that's how it seems from my outsider perspective
the logs were there somewhat put all over the place to try to find it , but in the game it wasn't switching turn to other player at times
anyway seems to work so far ! so who knows if it was just internal editor bug/crash in unity causing weird behavior .
Never happened on 2021
ty for you help @leaden ice
so i think i fixed the anhcor but it still dosnt work and the music also isnt there
Hey,
How to calculate the angle required to turn a vehicle?
Vector3 direction = destination - vehicle.transform.position;
float angle = Vector3.SignedAngle(vehicle.transform.forward, direction, Vector3.up);
int angleNormal = angle > 0 ? -1 : 1;
TurnHull(angleNormal);
This always causes angle to get stuck between 166 and -166 causing angleNormal to be 1 and -1 meaning the vehicle doesn't know where to turn and just turns in place forever.
c# deciding to use python syntax for switch-case for no reason:
isn't this backwards?
int angleNormal = angle > 0 ? -1 : 1;
Greetings, hoping for someone to have a look at this.
When my player faces direction 0, the determined input axis needed to rotate towards the mouse position is fine. However if I start rotating my player ship, then the axis keeps jumping between 1, 0 and -1.. and I'm not sure how to make it consistently just stay 1, or -1 depending on the easiest path towards target angle.
var direction = Entity.Transform.Rotation.ToEuler().Y;
//var direction = Properties[(uint)EntityPropertyTypes.TurretRotation].Int;
// Get the mouse position in screen coordinates
Vector3 mousePosition = Input.mousePosition;
// Calculate the target direction angle based on the mouse position
float targetDirection = Mathf.Atan2(mousePosition.y - Screen.height * 0.5f, mousePosition.x - Screen.width * 0.5f) * Mathf.Rad2Deg;
// Adjust the target direction angle to match the desired rotation
targetDirection -= 90;
// Normalize the target direction angle to be within the range [0, 360)
targetDirection = (targetDirection + 360) % 360;
// Calculate the angle difference between target direction and current direction
float angleDiff = targetDirection - direction;
// Normalize the angle difference to be within the range [-180, 180)
if (angleDiff >= 180)
angleDiff -= 360;
else if (angleDiff < -180)
angleDiff += 360;
// Determine the direction based on the angle difference
int rotationDirection = 0;
if (angleDiff > 5)
rotationDirection = 1;
else if (angleDiff < -5)
rotationDirection = -1;
// Set the direction value to your desired input or use it as needed
// For example:
ksReactor.InputManager.SetAxis(Axes.TURRET_ANGLE, rotationDirection);```
rather than reading euler angles use something like this #archived-code-general message
different question: Can I change the material of a particlesystem on runtime?
@leaden iceThank you. I cannot use signed angle however, at least not in that manner because I will be dealing with a single angle coming from the server, telling my client that "my turret is rotated to x rotation", and according to that turret rotation, I need to determine whether or not it is facing my mouse, and then determine how to reach it with an axis, so that the player can let the server know where to put it.
I'm using my player ship angle presently as a dummy until it is perfected.
your player ship angle is reading an euler angle back
which is the cause of your angst
is that what the server will be doing?
The server should use SignedAngle
The server is just updating a float that starts from 0.
You can also try https://docs.unity3d.com/ScriptReference/Mathf.DeltaAngle.html on it
even better
then you won't have euler bouncing nonsense to worry about
How can I make sure my game stays the same on all mobile resolutions. Its works fine most phone devices but if someone was to play it on the ipad, it cuts too much from the left and right side. My game is a endless side scroller. I know there are anchor stuff I can do which works fine for ui but how can I made sure all game objects also fit in all screens
The issue is it can't really be the same if the aspect ratio changes
you would have to do letterboxing or something to force an aspect ratio
is that a normal practice?
you can also do some math and set the camera's orthographic size according to the aspect ratio to show what you want to show
either changing the camera size or letterboxing
one of those
or changing the shape of the world according to aspect ratio
what would u suggest?
It's not my game
probably just setting camera size
The size value is explained here which you can use as the basis for any math you want to do with it:
https://docs.unity3d.com/ScriptReference/Camera-orthographicSize.html
Thanks It was flipped haven't seen that before, its been weeks 🙃
I'm having bit of trouble figuring out pathfinding for vehicles.
Is there a way to make NavMesh.CalculatePath not find the quickest route, but calculate a more central route. I already have baked navmeshes with ideal values but the pathfind algorithm always manages to find a way get off the navmesh by taking the very edge of the navmesh and clipping a fender on the side of house.
Hey, just curious - how do you guys structure your game managers? I have seen some enum-based game managers and I also heard about finite state machines, is it a good idea to use one along with a game manager?
"Game Manager" is an extremely vague concept.
It's different in every single game I make
some games need a more formal state machine
others don't
I see... and considering im making a small endless runner game - do you have some tips for that?
no need for a complicated state machine
Probably two scenes
Menu scene and Game scene
Yeah, something like that, so I guess the manager should just handle switching the scenes and maybe toggling some pause and game over menu?
perhaps
basically oyu're either:
- in the menu scene, menuing
- in the game scene waiting to start the game
- in the game scene playing the game
- in the game scene paused
- in the game scene looking at a gameover UI
so that game scene stuff could be a state machine if you want
but it's also simple enough it doesn't need to be formalized much
alright, sounds fair enough, thanks for your help! :D
does unity support nullable types?
public bool? MyNullableBool()
{ return null; }```
Unity supports everything in C# except a few noted exceptions https://docs.unity3d.com/Manual/CSharpCompiler.html
direction = tempRotation.eulerAngles;
rb.AddForce(direction * 500f * Time.deltaTime * ai.projSpeedBonus);```
thanks!
any ideas for why this will only add force upwards?
transform.rotation.z is nonsense
rotation is a quaternion
don't read .z from it and expect anything useful
don't multiply your forces by deltaTime, and reduce that amount of force when you remove that multiplication
Another thing is that euler angles are NOT a direction vector
aight so how would I go about getting the angle from the rotation?
what are you trying to do
project the rotation on the x/z plane?
Vector3 forceDir = Vector3.ProjectOnPlane(transform.forward, Vector3.Up);```
oh 2d
then
and transform.right gives me issues for some reason
what kind of issues
maybe you want transform.up
it dpeends how your sprite is laid out
I'll try it out
also yes get rid of Time.deltaTime and 500
yeah i gotta fix all my rigidbody settings in this project still
this is the first game I made so a lot of the early stuff is messy
I just set the direction to transform.right and it worked this time thanks yall.
If you're making a game in which the player gets surrounded by dozens of enemies, and they make footstep sounds when they walk... what's the most common solution to preventing a cacophony of footsteps?
Use an audio mixer and make sure you normalize the input
Otherwise they'll all add up and break your eardrums
you can of course also do some kind of pooled audiosource thing and limit the number of concurrent active audio sources
yeah i do that part already
normalize is a good tip though. do you generally apply normalize to all your mixing groups?
I'm going to be real with you, I only ever had one project that got far enough where I needed to care about such things.
haha hey thats one more than most 😄
For context: in that particular case it was sort of a tetris / bejeweled style game and when the blocks were eliminated they would burst into particle systems (sort of like a firework explosion). Those particles would fly over to the score counter UI and each particle would make a small sound when it finished doing so.
When you scored a big combo all the simultaneous sounds were maxing out the speakers and very unpleasant. Using the Normalize effect made it sound better.
@leaden ice oh man... i also did not realize you can add duck volume to a mixer group and add a send above it and send it to itself
Excuse me, I'm finding an issue when I try to make the enemy wander randomly they get stuck within the obstacles, I wrote the code that sets the destination anywhere else when they touch said obstacles, but they wont avoid them and will just get stuck.
[18:32]
https://pastebin.com/fUkn47gp
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How could I save a list to a json file?
use a json serializer such as Unity's JsonUtility or Newtonsoft JSON
public State.CombatState CheckCombatState() {}```
I assumed you could have methods with return values on interfaces but I get "Not all code paths return value"
The only place the interface is implemented returns a value. Are you just not able to have return values with an interface? Been a while since Ive touched C#
you're not returning anything there
Yes it is the method on the interface
I have to provide a default return value? Odd
you do if you provide a default implementation for the interface method. if you do not wish to do so remove the curly brackets and replace them with a semi colon
It works. I assumed you wouldnt have to with the default implementation
That works also
Thats stupid imo but it works. Thank you
you either declare the method without a body so it does not have a default implementation and your implementing objects have to provide their own implementation for the method, or you can use the default interface method where you've declared a body for the method so it must be a valid body, including required returns
Makes sense
Shader error in 'Universal Render Pipeline/Lit': maximum ps_4_0 sampler register index (16) exceeded at INVALID_UTF8_STRING(11) (on d3d11)
I get 5 similar errors while getting build
how to lock character in one rotation
simple - don't ever change the rotation of the character in your code.
Also if it's a rigidbody you would need to add a constraint on rotations otherwise the world could interact with it in such a way that it would rotate
does anyone know how to autoformat c# code in visual studio code such that the curly braces start on the same line as method declarations? (sorry if i'm asking this in the wrong channel, not sure where else to ask)
example:
private void method1() {
// i want this
}
not
private void method1()
{
// not this
}
if only there was some website with some sort of documentation for vs code so that you didn't have to break server rules by answering questions with AI generated responses.
oh wait https://code.visualstudio.com/docs/editor/codebasics#_formatting
didnt know, sorry
I created this little healthbar rendering manager script, it works well enough, but feels somewhat awkward. Basically the intention is that healthpools are just health amounts current/max, etc for a character. The HealthBarManager class is attached to a canvas, and determines which healthpools should currently be rendered, takes care of making sure the renderers are in place while the healthpool is on screen, recycling them when they are no longer on screen. Anyway, just looking for any feedback on the design of this 🙂
Camera.main is super slow. Don't call it every frame, cache it
ok better question what's a good formatter to use to format the code since vsc doesn't have default formatters for c#
while it is better to cache it, it is not super slow. It was changed years ago so its not using FindObjectWithTag anymore, it is internally cached.
https://docs.unity3d.com/ScriptReference/Camera-main.html
ah, good to know
I can never remember, help
If I have a class A, and a class B:A
and I have
A b = new B();
and I call b.GetType()
will I get A or B
you will get B
thanks
it'd make no sense if it was A instead, but I keep forgetting anyway
im not entirely sure but wouldnt it be better to just give everyone a healthbar renderer and simply/enable disable it when they are out of view. Then just keep pooling for assigning/recycling the health bars when they die or are spawned
overall i dont see anything wrong though
reason i didn't do it that way was because the healthbar is rendered on the canvas and i didnt want the characters to be children of the canvas, maybe there is a better way of linking 3d objects to canvas object though 🤔
this is the sort of heiarchy ive got currently
If it introduces complications then I probably wouldnt worry about changing it unless you had a ton of enemies and needed to optimize
You could probably just keep the current setup, and disable the healthbars on the canvas while the enemy is offscreen, while just not updating the healthbars position
When they come back on screen, enable and update position
thats currently what happens with the pool manager class. when the healthbar goes offscreen, it gets tossed back in the pool so whenever any other character with health comes on screen, it can be assigned one of the available healthbars, i figure it was a good idea since not all characters will be within the viewport at all times so this keeps the number of objects down a bit
so like if all 4 of those tanks are destroyed, the 4 healthbars will stay attached to the canvas but disabled, when it new tanks are created, as they come on screen, the healthbars will reactivate as needed and get assigned to the tanks as they come on screen
anyone knows if there is a method like AssetBundle.LoadAllAssets<T>() for addressables which takes an IResourceLocator as a parameter?
Are there some better practices to acquire lists of players/enemies/entities/items that are available in the level other than the basic options like below?
GameObject.FindObjectsOfType(typeof(SomeScript));
GameObject.FindGameObjectsWithTag("SomeTag");
Is there a better way to cache these items in a Singleton List on spawn or something? I'm not sure on the best practice here. Any ideas or references would be great!
which plugin is that?
Yes, cache them as you spawn them instead of finding them. Or get your objects to register themselves.
? its just the default heiarchy view that comes with unity
its actually pretty cool, and doable
i was joking about the colored lines
With a Singleton that handles this? Like a SpawnedManager.cs or something? Or are there better approaches? All of my items already have an OnSpawn Action that gets sent out, so having them register would be easy. I'm just not sure on approach, or best practice of storing those items.
separation of concerns
what keeps track of enemies? what makes sense to keep track of enemies? enemy system? etc
a generic EntityManager is also good, you can use dictionaries by types
Sure, whatever you want
The best practices in games are very "do whatever makes sense for you and your setup"
that's fair, so the approach really doesn't matter, it just matters that they are cached
depends, you can make a big mess if you dump everything into a single class and use direct references to strongly typed lists
if it can be neatly generalized, abstracted behind a single api its good, healthy
I might try an EntityManager with a dictionary or lists of each type and see how that goes. My project doesn't have a lot of different types, it's pretty simple. Appreciate the help. May seem like a simple thing, but I like to use good/best practices where I can, so I was curious.
I need help and I wasn't sure which channel to put this in. I made a lego wall in blender and in unity I wanna make it so when the player shoots a rocket at it the wall blows up into a bunch of lego bricks. I can make it so when the player shoots the wall the wall disappears and a lego block instantiates but I want it to instantiate a bunch of different colored blocks and have them spread out in a bunch of directions
Instantiate a bunch of them the same way you instantiate one. Then make sure they have rb+collider components and apply forces to them.
you can just have a prefab of lego bricks thats roughly in the same shape of the wall, then replace the disappeared wall with the broken up one. Apply explosive force manually depending on which area of the wall was hit
well how would i get the instantiated ones to have a random pool of colors
Use Random.Range to pick a random color from an array or use https://docs.unity3d.com/ScriptReference/Random.ColorHSV.html
thanks
wouldnt you want it to have the same color as the wall?
or else the user will just see it change colors randomly
yeah i guess your're right
does anyone know why my vertical meshes (the blue color shapes) are see through?
looks like you only made geometry on one side
triangles in meshes are single-sided
unless you use a mateiral that renders backfaces
hmm, shouldnt I be able to not see the blue faces at all then?
When I flip it back, it looks fine
But the order is wrong
top is down and down is up
thats generated?
I think the normals in this first image are inverted for some portion of the mesh
in this image the normals look correct
no thats not normals
yes
what does "flip" mean in this context?
that flips it upside down basically
where triangle will be facing is dictated by which order it was constructed
clockwise and counter clockwise
so you're seeing the back of many of the faces when it's flipped
which is generally not visible
unless using a special material
no, im using the sprite defalt
are you saying you made a hexagon out of sprites?
the normal mateiral would be Lit or Unlit (or Default in BIRP)
the only way it will work is if the material is opaque
or at least cutout
otherwise the alpha sort will fail at specific angles
im ignoring the fact that this is the weirdest way yet ive seen anyone construct a hex
the problem is this
The blue verticals are rendered from TOP to bottom,
so a hex that has a higher Y position will add blue verticals to its side
however, the generated mesh, with default orientation it looks as though the blue verticals are generated bottom to top
Nah, they are meshes
read on "winding order"
ok so you[re not doing procedural mesh generation
you're just using a fuckload of meshrenderers
yes
ok, will use quad
anyway it just looks like your code is not positioning/sizing some of these planes properly
and when you flip it upside down (why?) you won;t be able to see the backs of the planes
because you can never see the backs of the default plane mesh
(barring a backface shader)
the position are inverted,
for this picture +Y goes downward and -Y goes up, same with the Z axis
If i try and flip the image to properly match the axes, the blue things dont match
Is there a question in here somewhere?
I dont get why its flipped, my triangles are rendered clockwise
it just looks like your code is positioning things incorrectly
it's unclear what data we're starting with to generate this stuff
and what the code is actually generating
and of course, we haven't seen the code at all
if (Position.y > hex.Position.y)
{
(int, int) sData = OppositeCorners[i];
(int, int) data;
data.Item1 = i;
data.Item2 = (i + 1) % 6; // so the last one loops back to the first one
// the current hex's side vertices
Vector3 pos1 = GetSideVertexPosition(data.Item1);
Vector3 pos2 = GetSideVertexPosition(data.Item2);
// the surrounding hex's side vertices
Vector3 sPos1 = hex.GetSideVertexPosition(sData.Item1);
Vector3 sPos2 = hex.GetSideVertexPosition(sData.Item2);
int sv = SlopeVertices.Count;
int v = Vertices.Count;
SlopeVertices.Add(pos1);
SlopeVertices.Add(pos2);
SlopeVertices.Add(sPos1);
SlopeVertices.Add(sPos2);
//SlopeTriangles.AddRange(new int[6] {
// sv + v + 0, sv + v + 1, sv + v + 2,
// sv + v + 2, sv + v + 1, sv + v + 3
//});
SlopeTriangles.AddRange(new int[6] {
sv + v + 3, sv + v + 1, sv + v + 2,
sv + v + 1, sv + v + 2, sv + v + 0,
});
SlopeColors.Add(SlopeColor);
SlopeColors.Add(SlopeColor);
SlopeColors.Add(SlopeColor);
SlopeColors.Add(SlopeColor);
}
What the code is doing is getting those 4 corners and setting vertices and triangles
it does it for each side of a hex
so wait you are doing procedural meshes?
So in summary,
for each surrounding hex, we check if the surrounded hex is lower than the current hex, if it is draw the height vertice
I'm confused because you showed the Plane mesh before
yes,
I want to replicate the tilemap system
but with meshes
I mean there's a lot of moving pieces here
added the omnisharp.json file to root and pasted in the provided code and still nothing 😦
from this image for example it seems possible that GetSideVertexPosition(data.Item1); could be returning the wrong positions
I mean I understand that your procedural mesh generation is working improperly
I don't really see what you mean as a "dilemma"
I know it took me about three weeks to get a working procedural mesh system for building hesagonal pipes in my factory builder prototype
procedural meshes are hard
I don't really think "bottom to top" or "top to bottom" matters terribly much - either way it's connecting the lower and higher hex
everything is as it,
data is the current corner (the top 2 vertex)
sdata is the matching corners (the bottom 2 vertex)
Feels good to know its not just me
i mean these definitely look like numbers
no way of knowing from this screenshot if the y values are correct
they're certainly internally consistent
I see
I'd recommend using gizmos/handles to visualize this stuff in the editor
and make sure it matches up with expectations
btw https://docs.unity3d.com/ScriptReference/Handles.Label.html was the magic sauce that let me fix my procedural meshes. Actually rendering the vertex numbers in 3d space is a gamechanger
the question is way too vague to be answered honestly
it depends on what these things are, what they do, how they interact with the rest of the game
answers range from basically... strings to enums to ScriptableObjects
it really depends on the needs
inheritance is usually not the best way, I'll say that
could be
that's kinda similar to SOs
You can replace the strict inheritance hierarchy with interfaces. Create item classes based on functionality and add various interfaces based on the features of the item to expose them to other systems in the game.
You could try composing the items with components or by other means, but settings exposed in the inspector can often handle a lot of variants.
guys I need help with an error I am getting and I don't why it appears. The issue is that is it is random:ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <4911eca47f294e18a7b3306f02701303>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
looks like an internal unity editor bug
I remove a variable that goes a little bit like :
[SerializeField] public Transform parent;
and it seems like the issue is gone for now but I don't why
I was dynamically creating sprites and put them as child under a specific parent I wanted
at least for now, it seems like it is fix. Sometime, it work fine for hours then later I got errors like this
Parent is a property of Transform that you cannot set to null. If you've got your own variable called parent, make sure you're setting that variable and not Transform's parent property.
This is a common error seen recently and unlikely to really have anything to do with your code
Updating to the latest patch version might address it
ah man thx
I will update unity ig
I have worked with c++ before so getting errors gave me a trauma with null errors
I am using this method to rotate my camera and the new input system, how can I go about clamping this rotation so it doesn't rotate more than -90f, and 90f. thanks!
(the value from the input event returns from -1 to 1)
Accumulate rotation deltas in a variable and subtract the excess amount from your calculation before rotating.
hmm thanks
If that's mouse input, you shouldn't be scaling it by deltaTime
how do i get angle diffrence but wit hpositive and negative value?
vector3.angle gives just positive
Is there any easy/handy way I can add a "test" button as a component in the editor or whatnot, that I can click to invoke methods on mono behaviors and etc?
not a button in the scene, but like one I can click in the inspector? Ideally with as minimal effort as possible just so I can test out that when the method is invoked, it does what I need it to do
as an example I wanna test out Kill() methods for dying enemies in my game, so ideally I just click on the enemy in the editor, swap to game view with inspector open, and click a button in the inspector on the component that'll just call the method directly so I can make sure the method does what I want it to do
if you use naughty attributes or odin, both of them have Button attributes to call methods from the component inspector. otherwise you could create your own with some editor scripting
do they add any overhead to the actual game I compile or is it purely just editting tools?
if you put it in a folder named Editor, it wont make it to the build
yeah you keep all your editor scripting in an Editor folder since nothing that uses the editor will actually be compiled in a build
gotcha
The easy thing to do is just decorate a method with ContextMenu and then you can right-click your component and call it
https://codeshare.io/mp9RY4 Is this spaghetti code? 🤔
it's for a chess application
probably, but i doubt anyones really gonna take the time to go through that and try understanding it, this is a pretty bad way of writing it. Its really not readable, not commented, and you definitely dont need to chain so many linqs together. Imagine u are a new developer trying to understand existing code and this code is the first thing you see
yeah my first version had many nested foreach loops and if statements but I had too many so I tried to use Linq to get less nested stuff but using Linq was also a mess
new { variation, move } is this an anonymous type 
a short explanation of what it does: the string moveNotation as the parameter might look like "d6 Nf3 e5" so what my code does is it looks for a variation that has made all those 3 moves in the same order
you should just stick to the foreach version, i guarantee it'd be more readable
ye I needed to return variation depending on what move is
but I don't like to have more than 3 nested brackets like: { { {
then make a method for some calculation
yeah I guess
anonymous types are truly disgusting, just use a value tuple
https://codeshare.io/1YmOkn here is my version with foreach loops
oh I did ToList on the split for no reason 😂
i think you should probably use one of the !code sites listed, it seems like i can edit that link lol
📃 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.
just incase someone decides to put something bad in there
the foreach version is at least more readable than the Linq version 😂
but it has too many nested stuff
uh you can't edit that one right?
i wouldnt say its so bad that you should refactor purely because of the nested statements here. I also dont know what the code is doing so its hard to say if you even need all this, i understand the goal but most of these values dont really mean much to me.
yea cant edit
do you know how chess move notations works?
cuz that's part of what my code does
yes, ive played chess a bit but i dont know what a chapter is
a chapter contains variations and a variation contains a list of moves
so it's like a book kinda
so a variation is could be e4 e5 Nf3 Nc6
and if moveNotation is e4 e5 the method will return that variation
but it will not return that variation if moveNotation is e5 e4 because that's the wrong order
so currentComparingMoveNotation makes sure I do it in the correct order
what are you storing this for, predetermined AI moves?
the moves are from a book that I've purchased so I pulled all those moves in to my app
so this method is like asking "when do I play e4 and d4" for example
and it's a Dictionary so it doesn't get multiple variations with the same position
Yes man
Youve definitely misused linq
https://gdl.space/uxujidogoy.cs have a look at this version which does the same thing
For each looks fine to me
okay
im still confused what you would actually use that for, sounds like some chess learning app. From the problem it sounds like you do need all the nested statements, but i almost wonder if itd be better storing all the related variations in one collection then searching through that instead of calculating a subset everytime.
Chess related calculations always suffer from performance/memory issues though so you'd probably have issues either way
the reason I made this method is because while I play chess in the opening stage, I somtimes ask myself "when do I play d6 in this opening?" Or "when do I play both e6 and d6?" and this method gives me all the variations that answers questions like that so it's just a way to find what I'm looking for quicker
all the sites that do something similar to what youve described just have massive databases, at least from what ive seen
its a memory vs performance tradeoff, where these sites have the money for memory
there are many apps that don't have all the features that I want so I made my own app with a mix of features that I want lul 😛
it's also for personal use only
You have a list of all of the variations
yeah but the list of moves are in the list of variations tho
If you are looking for kd4 rf2
you would have a list of every variation, which is what i suggested here
Just find it
Yeah basically a big database
Which isn't much different from what you have right now
Hello
true 🤔
especially if its just on your pc, memory shouldnt really be an issue
Depends on how many pages the book has that he purchased 
this is my "database" 😂
you can easily hit 1m+ lines on a database, though with chess i imagine that'll be not much
yea thats not much
my first job i opened a "database" of 2 million entries with 50 columns each. This is lightwork
it was in excel too
Ye this shouldn't be a problem
but I'm using SQLite as well so the first time I run the app I read from the json files and add them to the SQLite database and the next times I don't need to read from the json files
it did take like 2 minutes to open though so id go get free coffee everytime i had to open it lol
And this where your caffeine addiction started...
That's cool, I guess
But you can just have it in memory if you have a simple structure
Isn't sql lite in memory as well?
If it isn't you'd still be dealing with your IO
i would still just add each variation, im mostly sure sqllite will be fine but you should run through it and calculate how many lines you'll be storing to make sure its not like over a few million
ive never used sqllite so i dont really know about it specifically
Also if performance is important look into an algo like this one
Hello, do you guys have any ideas how to make level creator mini-engine in Unity?
Probably like e.g. level creator in Geometry Dash, where players can create their own levels and play them.
Let's not talk about making it multiplayer, how do I implement this so that just I can create levels in my own game?
Everything that is instantiated in the game - stays just in game and doesn't affect editor.
How do I save levels and then make me able to use that levels?
Even e.g. instantiating prefabs on random position when pressing space button. Then when game is finished and prefabs are spawned, this (I think) Scene should be saved somewhere.
Maybe that shouldn't be done in game, just in editor ?
Thanks for reading
In computer science, the Knuth–Morris–Pratt algorithm (or KMP algorithm) is a string-searching algorithm that searches for occurrences of a "word" W within a main "text string" S by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing ...
You wouldn't create a new scene
