#archived-code-advanced
1 messages · Page 141 of 1
yeah so that's an issue there
you can have the class inherit from the base, and the base inherit from mono
or you can use an interface
I can try to transfer that property into one of the classes Ive made.
No dice, it has fields that requires the properties on the other base class.
There we go, something like this.
cool
So declaring the properties like this, I may be missing something, and how can I get the property CalculateCollectedStars() which is in the actual MonoBehaviour parent?
Properties need a name, just like your filename field
You currently have access_mod type;, and you need access_mod type name;
Noted thank you. Now what Im missing is the property within the Monobehavior.
Which is this one.
The code is indeed correct. Im trying to add it unto the base class, which is DataExcel.
Which is a child of another base class, Monobehavior.
Which CalculatedCollectedStars() is actually under.
So you have a ClassA : MonoBehaviour, a DataExcel : ClassA, right?
Yes.
Just making sure as in that screenshot it wasn't the case.
For Clearance, Both Shape and Test are children of DataExcel. And I declared DataExcel as a child of Monobehavior.
The reason I did this is because they have fields that i need to acquire.
My problem is that CalculatedCollectedStars() is another field I need, but it's under the parent of DataExcel.
When I about to make the string ForLoop, How can I call on CalculatedCollectedStars? Just call them all the same under MonoBehaviour?
If I understand this right, you could create an abstract int CalculateCollectedStars() in DataExcel, and have each child class Shape, Test override it. Then you can use your regular foreach loop to call CalculateCollectedStars in DataExcel.
Let me try.
Stated that virtual or abstract members must be private, despite the screenshot I shown you of it's actual code put to public.
You definitely can declare public abstract members -- are you getting a compiler error?
Yes.
What's the error message?
cannot be private, not must be private
Ah, my mistake.
In depth: Declaring something as private does not expose it, even for child classes (compared to protected which does), so the child can't override.
When i try to apply override to either Test or Shape, the error Im getting is stated to be not valid for this item.
Not valid? Normally your override signature would be something like public override int CalculateCollectedStars()
Same return type, same parameters as the abstract declaration
These are the errors im getting.
Show the code of the method in DataExcel, it's originating from there
Looks like it's not marked abstract
Weird. Have some sample code
public abstract class Base {
public abstract void Method();
}
public class Child : Base {
public override void Method() {
// Implementation
}
}
Call
Base b = new Child();
b.Method(); // Calls on Child because that's what really is in the variable, even if VS highlights it as a Base
I should put the call within the Implementation Method?
That call was an example, in your case if you have a List<DataExcel> you can call it on a single item, in your foreach loop
I think you're reversing it
Abstract goes on the base class so the children can override it
And abstract does not have a body, overrides do
Switching between the two still offers the same errors.
Then see my example again, as I'm 98% sure my version compiles nope
Haha damn, I get it, abstract methods must be declared in an abstract class
Mark DataExcel as abstract.
(original code snippet edited)
Ive gotten this one now on.
Yep, so in that class declare the override and provide your own implementation
You need to post the error messages. It will be faster like that
Please refer to the two pictures I posted. They're still the same.
Then post the updated code. There's still something that the compiler doesn't like
Wait why is the abstract method suddenly in ShapesManager? And why does it have a body?
There's something about your class architecture I'm not getting
Give me a bit, for you to have a better picture ill give you the entire code through a code bin.
Alright
The important ones are DataExcel along with the child classes. The WriteCSV below is where i need to put my ForLoop on, specifically the lower WriteLine code.
Yeah the abstract method must be declared in the abstract class DataExcel. Then all the classes that inherit from DataExcel override the abstract method
I think the whole class complexity and the abstract/override layer on top is screwing your perspective of it
what
Why is the override on the class now
That's my mistake, as you said, it's screwing my perspective.
I think that whole thing is beyond your knowledge for now
I suggest taking a step back and learning how it works in a separate project
How do I make a 12 hour timer that runs when the app is offline?
Yeah. I have to tell to my boss that the code complexity for class may be too lenghty to implement on a rigid code structure like this one, along with the fact that's it's beyond my knowledge.
Still, thanks for the help.
Google, don't cross post
What?
I was about to answer you in #archived-code-general
I don't see how you'd make a timer run while the app is closed
Do you just want to track the time between sessions?
I am making a system that every 12 hours it resets the prices of a object.
I was thinking to get the current system time and if it is 12 hours or more past then it changes
That's the best way, as you can't add a timer on a process that may or may not be running
And even if you create and run a separate process, they get stopped when the computer shuts down
So yep, comparing the app startup time to the last app shutdown time would be the best solution
I have some problems with camera follow in a multiplayer game, I would be grateful if anyone can help me out?
Have googled but dont find any good solution
The lerp works fine, smooth movement but camera always stays on side, no matter what code i use it doesent work
Camera is separate and are looking for player transform
Vector3 lookPos = character.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 4.0f); ```
I want it to stay behind player without parenting it..
@bleak gorge that sounds like offset is being calculated improperly?
people can easily doctor that by changing their system's time manually, I would suggest perhaps using API to get the time via internet first, if internet isnt detected, fall back to system timer.
Yeah but I don’t really care Cus I want it offline and online and it’s not like it messes up the whole game but thanks
Hey, not sure if this is really "advanced", but couldn't find anyone even asking about it, so, I guess. I have this problem where I want to display a world space text prefab over a certain boundary, nothing too hard(not that I would know how to do that, but a quick google search could probably help), but the boundaries are defined by a list of gameobjects so I somehow need to combine their colliders(or if theres a better way, please tell me.)
Btw, it is really important that these gameobjects are seperate objects for the game I am making.
So, just not making them a list but one object is impossible
what do you mean by over boundry? Like clipping through other objects? having a physical collider colide lettering with other objects?
No no, I am making a strategy map game
And I need a country name to display over the country
Which is made up of provinces
ah like a paradox game?
and the text needs to arc/curve squeeze to fit in an irregular shape
Correct
The shape being of course made up of provinces
Which are stored in the list
ok first stem is to compost the provinces together to some kind of 'mask' shape
I dont think I get what you mean
and then a fitting of a generallized arc across that shape in an orientation thats readable (I assume north will be fixed upward on the screen)
lastly TextMesh Pro your name into that arc
Yes, but I dont get what you mean by mask shape
ah well the shape of each individual province, you have it stored as something right?
Correct
you need to stictch all that together into one shape first, by 'mask' I meant the combined shape
Ah, I see
Well, how do I do that?
I cant just unite them into one gameobject
Thats the problem
depends on how you implemented the shapes
how are they stored? the stitching together will be dependent on how they are defined
no I mean how is the shape defined
With colliders?
ok see the green blob in your example, that is a province correct?
oh so the provinces are just squares, and you have a list of the indexes of provinces that are part of the country
Yes
Although they wont stay squares
But right now they are
(Btw sorry for my bad english, I'm not form an english speaking country.)
ok well you could either write something simple now that assumes squares and then rewrite it when they change to other shapes
Yeah, thats why I came here, I have no clue on how to unite colliders
Because in order to display text over them the need to have one border, correct?
don't worry about uniting the colliders, you only need to worry about uniting 2D shapes
but your text will be 2D right?
also is this land? like is your 3D just for mountains/texture etc like in paradox games?
Yes
If i get what you mean
If you mean, is this a plane? then no, those are individual cubes
ok and the Name to display will it be ok if it's ignores the 3D terrain, like the you want the text to be undistorted by mountains and such?
Nono, it will be higher than terrain
so no problems there
and it also wont be transparent enough to get distorted or unreadable
ok then it's definitly simplifies the problem to think in just 2D, resolving the shape of a country into a 2D shape
Is your world something odd like a simulated sphere or is it the more traditional wrapped cylinder?
or even just a flat plane
flat plane
but if you go to the edge it loops your camera back to the other side
so it simulates a sphere
but its a flat plane
like the game Asteroids?
I dont know what asteroids is
we call that a Torus world actually, if going off one side of the map takes you to the opposite side
I just remembered the term
Screen wrap
It simple screen wrapping
So, I guess torus world is the correct term
but Im not sure
dose going north cause you to apear on the south edge of the map? cause that's the key difference between torus and cylinder
not really
Because I havent decided if you can rotate your camera, because if you cant you would end up upside down, but if you can, it would feel kinda off
So, I guess no
Atleast for now
so, cylinder it is
I guess
ok well combining individual provinces is the main challenge, even in 2D their are many ways it could be done. My sugjestion is to just create a seperate object which will hold the 2D representation and translate the provinces 2D 'shadow' onto it
Maybe I could use the existing country object which already holds the country script and stuff
that's a resonable place to put the code and store the resulting object
This is my hierarchy rn, so how would I do that thing you just said, with one of my country objects
The photonplayer is of course there for testing
I'm not entirly sure how to do it myself, I'm just looking for a general course of research you could follow in figuring it out
look your translating a 3D object into a 'shadow' aka a 2D silloute
Yes, yes
and for how to then composite these shadows together, this can be as simple as using a texture alpha value
okay
How tight fitting do the worlds need to be to the country? Is any overlap unacceptable?
They can overlap a little
like if their was a tiny little country inside of another
ok then just pasting the name right over the 'center of mass' so to speak would be adaquate
if a country had unconnected parts though would you want the name repeated for each part?
Probably
I have tried using CombinedInstances before to combine the colliders and get the center but something just doesnt work about them
So, you have an idea on how to get the center
?
well you could get the mid point between the farthest edges fairly easily
but a 'weighted' center is more complex
and detecting disconnected pieces is important, or else your weighted center might be outside the country
I think farthest edges is okay
Just implement a little check with trigger colliders or something
that it isnt out of borders
if it is seperated create two instances
If you had the countries shape defined, and then evaluaded each disconnected part seperatly to put a name in it
The shape is defined, my problemm is that it is seperate gameobjects that define it
take the country chunk and make a 2D mask with it, invert it so the collision is the non-country space. And then start growing a name inside of it untill it hits the edge, and you would have the largest possible name
you could even back up and rotate/bend the name to what ever degree you find acceptable to make it fit
Yep, that would probably be the best way
Now, making the 2d mask is the last thing in my way of good ui
Also you might want to try looking how Paradox games do their names, as they clearly figured out a solution for this problem
Yes, I know, but Clausewitz Code isnt really readable to me
Well, it is
But they handle everything way differently
yea different engine, at best a general strategy is all you be able to get
but in any case a 2D mask and compositing them together is a well understood problem you can likely search for solutions too
Yeah, you have any broad topic I could search for because searching "combining objects" or "2d mask of 3d object" isnt rellay giving mme the results I want
Yeah, the second one is giving me some good results
Thank you for your time
You were really helpful
your welcome, good luck, oh and out of curiosity where do you hail from?
Im german
your english was not an issue and I won't have know you weren't a native speaker if you hadn't said so
Well, thank you
I dont know if you are a native speaker, but in any case yours is also very fluent
my spelling on the other hand...
Is very good, what do you mean?
Except for some exceptions, like 3 (which can honestly happen to anyone), i barely noticed
well I'm just very bad at spelling generally, without spellchecking it will look terrible
just bad, I spell everything phonetically
If I was Italian this would not be a problem
but English spelling has next to no connection with how a word is pronounced
That is true
that's funny I want to do the opposite with a game project 3d into 2d 😛
I am making a system that every 12 hours it resets the prices of a object. How would I do this?
(Feel free to @ me)
I was thinking to get the current system time and if it is 12 hours or more past then it changes
Current system time can not be trusted. Get your time from a trusted source @exotic basalt
Doesn't really matter if it's an offline game
Depends if you're okay with a game that can be abused by modifying time. If it's extremely casual then it may not matter. If it's not, then system time is not okay
You don't have much of a choice except to trust it if you've a local game
I once used a product that used system time to evaluate its 30 day free trial 😆
you can use worldtimeapi.org for development, not recommended for production as their faq says
Probably doesn't matter, the people abusing it were likely not going to buy it anyways
Offset is just a vector3(0,4f,7f), i have hard times understanding that functions,
Do you have any idea what i need to do?
What server solutions do you all use? There are already so many different reedit threads on the different solutions and weather or not it is a good idea to make your own. What do you guys think?
Many real projects that require max. performance use custom net-code, a custom (virtual) server on an established cloud platform with a scalable architecture. This means different things for different projects and can't be generalized. Also depends on how much money you have. What you don't do is build a server in PHP/Node using HTTP and a REST API.
Custom
Eh, a php webserver can work fine
Lots of games probably still run on something like that
i said "need performance"
and the point was more about the REST/HTTP thing
"offset" is controlling the offset between the camera and character. That means 0 units in the x-direction (usually rightward), 4 units in the y direction (usually up), and 7 units in the z direction (usually forward, but can switch between left/right and forward/back depending on the rotation)
Hey, I'm making a cursed FPS game and I want my player to teleport around the map when I press a button. But I don't even know what to search or how to start making the script.Anyone know what to do?
Randomly teleport, or set waypoints?
randomly teleport on set locations
Ok, make an array of Transforms for your positions (Or Vector3's but I'd use empty GOs) then get a random element from there and set the player's position to it's position
ah
Wait, why an array of transforms. Why can't I just create a few empty GOs and then tp to them randomly?
yes emtpy gameobjects you can store them as type Transform
ah, alright
How might one develop a coordinate system for tiles on a goldberg polyhedron (geosphere, hexsphere, there isn't really a catchier name)
Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak
how do i find whatever the fuck is causing this??
im getting serious lag from this
http/rest for persistent data and sockets for realtime duplex data transfer
and it happened randomly after building
It's internal most likely. If it's your own code make sure to turn on leak detection to find the source, assuming you use com.unity.collections
idk how the fuck to remove com.unity.collection
watch a video to remove i
it
and it literally automatically adds itself
if i close my project
its like a cancer
i even downloaded entities
like other recommended
you're probably using a package that depends on it
Entities for instance does depend on it
thi is causeing my online game to be neeerly unplayable
and i only added a single listener in player bases looking to see if the player can move
if(bool){ move();}
Would inclusion of a package have any impact on your game if you're not using it?
its online so, im using playfab for user IDs and using mlapi
my database is just a server side http to aws arurora DB
I remember a guy wrote about how he solved it like a month ago, so check #archived-code-general if you can find the post
Can't remember his exact name though unfortunately
Rockin
Can you remember any key words he used in his post, so I can use the search function?
mm nice
omg unity
XD
Not really no, maybe some of the words you used?
I'm not sure what I'm supposed to be looking at, but I to feel "omg, Unity" quite deeply
@novel wing https://docs.unity3d.com/Packages/com.unity.memoryprofiler@0.2/manual/workflow-memory-leaks.html how the fuck do i atach the memory profiler, doesnt even say where to find it in unity. omg unities documentation is sooo bad for first time use.
Attach the Memory Profiler to the running Player. For information on how to do this see Capture a memory snapshot documentation.
okay, how about 1. is WHERE the fuck i find it
jesus christ
lol
i dont have memory profiler
would entities do fine? lordy
@novel wing what is GhostStatsSystem
thats the memory leak
Can you stop tagging me on every single post you make?
DOTS is still in preview of course shit's going to be broken and buggy. Check the forums or #archived-dots if the docs are insufficient
hey guys, i need some help with a combat system, is there a good tutorial on where to start?
it's for a fighting game so i just need a ability/moves system, a damage system, a buff/debuff system, maybe a consumable system, but no need for an inventory system
Most likely not. And if there was it most likely wouldn't work for your game's needs.
at some point, there are no more tutorials, basically if you ask in advanced code, tutorials are over.
Again, thanks to no one, i found the issue and fixed it. God seriously wonder sometimes what this discord is even good for..
oh ok i just thought that this question would go here as people didn't answered me on general
I can point you in the right direction. You most likely will want to use ScriptableObjects for buffs/debuffs. For an ability/move system this really depends, maybe a finite state machine could be used?
the question is very general, no simple answer, and nobody fancied getting into a long discussion.... probably
ok, atleast it seems i am/was on the right direction (i'm already trying just having some troubles on the interactions), well thanks! will try to search more, sorry for posting here
Dude, it was 45 minutes since you asked. This isn't a live helpdesk, if people are around and know the answer and have time, they will answer. It helps though if you ask questions in a polite, clear, and concise way.
All good! Good luck, and if you have more specific questions you can always comeback to ask (either here or #archived-code-general depending on the question of course)
ok thanks!!
#if UNTIY_EDITOR is resolving as false even though I am not trying to make a build
how do I fix it?
Did you typo it in the code as well?
UNTIY ?
Hello chaps, does anyone have any idea how I could go about generating a random number based on some input, Ideally it needs to be seeded so for example, say you visit vector 0,0,0, then you got really far away and return back to that position, I want the same items to generate in the way they originally generated. My end game is to create a procedural road with some simple turns in, and when you return to certain parts of the road, you see the same turns and generation as when you were last there.
Using random.initstate() is not viable because I cannot control the generation order
Try storing the vector's hash code theVector.GetHashCode(). It's an integer value that, if well implemented, should be unique for each vector.
ill give it a try now, I did try a couple of hashing functions I found online, and that worked however the numbers I was getting for each vector were insanely huge
You'll also get huge numbers, maybe even negative numbers, but still contained in an int, so not that big. Shouldn't be an issue
Yea I am getting some more reasonable numbers at least now
seem to be unique for each vector position and I get the same return when I input the same vector
For it to work, you'll also need to check that two new Vector3 with the same XYZ values return the same hash code
Oh alrighty then
Only problem is, how could I implement a seed, so its not the same outputs for each game, I guess I could just multiply the hash code by the seed?
Sounds reasonable, if the seed for a world is unique
You could make the seed a Guid and get the hash code of it, then use that to multiply the vector hash codes with it
yup, I could probably just get away with a random int or something
Reduces chances of collisions
that would work also but possibly a bit over the top, although yea as you said collisions could sprout up
basically the biggest downfall of hashing
Well thanks for your input @fresh salmon , I think this gives me a decent place to start.
Vector3 hashed to integer cannot be unique… best case is each hash can occur for 3 different vectors…. Also, I’d try to make the deterministic part of worldgen integer based…. Just more robust
yea I didnt mean unique as in unique on each game instance
I just meant unique compared to other vectors, but I understand your point
You tell that (0,1,2) and (0,2,1) have the same hash codes? Better check that, if that's the case then the implementation is bad
basically yea, I just need a deterministic way of generating random values based on some input such as a vector.
0,1,2
0,2,1
All good!
Does it have to be a float vector?
I mean ideally yea, but int would be fine I think for this application
Cause, unless you store that vec3 for future reference you are very likely to never find it again
I think maybe I would need to get deterministic values using some sort of grid based system then
And if you use a grid, you can just use integer vectors
because you are right
my thoughts exactly
because you are likely to return to the same grid
but not float vector
as you said
For that application they don't need to
Player visits position, hash code is stored.
Players wanders around and comes back to the same pos, the hash code is compared with the ones stored into the collection
So I would generate a deterministic value for each grid?
maybe I can visualize my problem better for you
And you could also use a HashSet<Vector3> or a Dictionary<Vector3, ?> to store the cached positions, and eventually some value linked to them
Same principle as before for float vectors… jzstvthat you can actually return to them
For stored float vectors you‘d maybe do a nearest neighbor lookup…. For that you need a tree optimized for spatial lookup
the only parts I am needing to procedurally determine are where a turn should take place
but importantly you should be able to travel 1000 miles out, return to the same position and the turns be the same
if this makes sense
I think a solution like this would be overcomplex for what is required
It does… that’s how all proc-gen worlds work
Hehe, maybe…. But those can be found on GitHub and used almost like a dictionary
So how would you suggest approaching this problem? I mean I was origionally thinking I would place a turn tile based on a random number associated with that tile/position
So maybe for example if the generated number associated with that tile can be divisible by two, there is a chance a turn tile could be placed there.
That could do it for a simple system like that
Hash code divisible by some prime number? That's a left turn.
Divisible by some other prime number? That's a right turn
yea something along these lines
it just comes down to how to generate the number for each tile, and how I would get the grid system implemented to work with this.
There are a couple of abstract grid systems (grid math libraries) on GitHub that would help with this.
Yep, making the link between the grid system and the random number is the difficult part. You have to adapt it according to what the link can do (get a grid pos from hash code, the inverse, both?), and what you're planning to do with it
ok I think I have some what of an idea of how I could do this, some kind of lookup to get the current grid pos which would be a integer vector position and then possibly use the hashcode of this int vector along with some sort of division check to consider what the tile should be.
Maybe,
anyway, appreciate the help guys, ill give it a shot
Just remember that if you're determining turns using division, make sure to divide with a prime number so you don't possibly get two "valid turns" for a single cell!
A very good point, thanks, its that or for example if the number can be divisible by 2, I would then pick randomly between left or right. But dividing by prime numbers may be a easier and cleaner solution, perhaps even slightly more performant as it eliminates an extra operation.
I would pick randomly between left and right
No! Because if you come back to the same position there will be a chance where the turns won't be the same due to the RNG!
The generation should always be deterministic (is that the correct term?), ie. always the same for a specific value
And just realized, your drawing above has effectively a case where there are two turns for a single cell, you might not want prime numbers after all, but two numbers where there is a low chance of a hash code being divisible by both of them at the same time
It all depends on the structure of the map you want to make
anybody good at checking 3d player movent scripts for me
yes
- i have a generic
Shooter<T>class that can spawn any projectile as long asTis a type ofProjectile. each of my boss enemies have around 4-6 of them (attached to their own child gameobject) that get enabled one by one based on its life count (first one starts enabled, second one gets enabled once first life is gone, etc.) - inside the class contains a
System.ActioncalledAttackStartActionthat gets invoked inOnEnable - my UI system wants to subscribe a method to that action so that it can display an attack name string on the screen when the attack starts
but i can't think of a way to loop through the Shooters and grab each Action.
because if i do something like
for (int i = 0; i < boss.transform.childCount; i++)
{
boss.transform.GetChild(i).GetComponent<Shooter<Bullet>>().AttackStartAction += OnAttackStart;
}
void OnAttackStart() { /*show attack name*/ }
then it'll only find scripts of Shooter<Bullet> and not Shooter<Laser> nor any other T that inherits from Projectile
but if i do
boss.transform.GetChild(i).GetComponent<Shooter<Projectile>>().AttackStartAction += OnAttackStart;
then it'll find nothing 'cause none of my projectiles are exactly of type Projectile, they're all some class that just inherits from Projectile
is there a good solution to this?
define an interface for Projectile that exposes the AttackStartAction, and use GetComponent on that interface instead
oh wtf you can do GetComponent on interfaces
I have no idea where to ask help for this 😄
I have many dynamic sprite renderers in a 3d world and when all they are on screen 50% of CPU ms get on this script:
CreateSharedRendererScene. If I hide all sprite renderer CullScriptable takes only 1ms vs 10ms with sprite renderer visible. I have also disable dynamic occlusion in debug mode but nothing different happened. Any help? thank you!
Are they all visible/need to be visible at the same time?
yep, I'm hiding these gameobject in other way and distance draw is not so big. So I really don't care if unity occlusion is working on these spriterendere. Even if the system is rendering a sprite that is behind a mesh it's ok, it's not so bad in performance
I'm testing now with deep profiler to see better
I'm not sure if you can disable frustum culling for specific objects...
for testing purpose I'm able to disable frustum culling on every objects?
deep profiler is not helping me a lot. still 10ms on this function when many sprite renderer are on screen
Not sure about that either. It's part of the render pipeline afaik.
ouch, not good having 50% of cpu time on culling script when culling is not needed 😦
Consider that all that cpu time(or more) is probably going to go into draw calls instead.
What you could do is use gpu instancing or combine the meshes into 1 mesh.
yep I know, but now 50% of cpu times gets in "CullScriptable" 😄 profiler is from a build, not editor
Probably the same thing. Or did you change anything?
public float spawnDistance
{
get { return _spawnDistance; }
set
{
_spawnDistance = value;
Debug.Log(_spawnDistance);
CreateTrackElements();
}
}
float _spawnDistance = 0.2f;
Is there a way to make spawnDistance show up in the inspector?
all i could find were workarounds :/
https://stackoverflow.com/questions/40554418/in-unity-can-i-expose-c-sharp-properties-in-the-inspector-window
You can make _spawnDistance show up (and be serialized), but changing it won't invoke the setter of spawnDistance then.
(Or write a custom editor if you deem it worth it, then you can do whatever)
yeah, thats the problem
I want to have a track with customizable distance between its elements, having it update live in the play mode as i fine-tune the value in the inspector would be nice
I mean I dont need the setter to work in editor mode, but i want to be able to mess with the value in play mode and have it update automatically
hmm
i could use a slider ui element and connect it to setter?
With your own UI (in-game or in a custom editor) you certainly could, yeah
If it's only in play mode, you could also just check if the value changed in Update
or in OnValidate perhaps
If you change the Inspector to Debug mode, it will show all fields, private or public, serializable or not.
hey guys, trying to refactor this but failing hard:
into something like this:
In the second image, try casting to T, not type
(and remove the type parameter entirely)
You shouldn't be needing the type argument, just cast to T in the body
And there's no reason to cast it from int to the enum type and back to int
Idk, doesnt show up
get { return spawnDistance; }
set {
spawnDistance = value;
Debug.Log(spawnDistance);
}
}```
That's a property
EnumPopup takes and returns Enum, not int
like this?
i need a setter
If you need to serialize the field, then serialize spawnDistance
You won't see properties, but you can see fields. I don't know why you posted a different version of your spawnDistance property. The other one works, this new one will cause an infinite loop.
Using debug mode for the inspector just doesn't help with the problem at all here. The goal is to invoke the setter when changing the value, debug mode won't do that.
Oh good spot, it's a stack overflow right here, got thrown off by the naming of the property
My bad, I read the question wrong.
hm, looks like that might not work with generics then. You can probably just ignore the actual type and cast the index to Enum and the returned value to int directly, I think
Yeah you can't as an Enum is not always on an int, could be a byte or whatever. A solution would be to cast to object, then to int
I can just do this to get rid of the Int
That boxes the value, but should be only a minor performance drop
What's the error message? "Cannot convert int to T" right?
yes
There should be a workaround with Enum.GetValues to get a value by index
JESUS IT JUST DONT WORK(wallruning
Update: Can you try with something similar to this? It could work using Enum.GetName
Haha it won't work actually, the arg expects a type T and that method returns a string
Yeah, a generic version of EnumPopup could be handy here, but there isn't
You would need a Dictionary to link an int to a T and use that somehow to pass that to EnumPopup
public T Test<T>(int val) where T : Enum {
T[] values = (T[])Enum.GetValues(typeof(T));
return values[val];
}
This seems to compile and return the expected value
That will not work for enum values with a gap in them though, or anything else where the array indexes don't exactly map the enum values indexes
its working
though I feel like I have done it in a very stupid way
wait, I feel like I have lost complete reason of why I was doing this
ummm
lol
thanks a lot for the help, need to take a step back and take this all in
Holy hell, that's what I call shitcode. That version will work with enums with non-linear values
public static T GetEnumValue<T>(int val) where T : Enum
{
Dictionary<int, T> d = new();
foreach (int value in Enum.GetValues(typeof(T)))
{
d.Add(value, (T)Enum.Parse(typeof(T), Enum.GetName(typeof(T), value)));
}
return d[val];
}
I hate what I just produced
why don't you just cast the enum ?
Yeah I expressed it above and it works, then we got lost in all that
is it really shit code when dealing with serialization and adapters... they often have to bridge language barriers and having reflection in your language to make that somewhat simple is a godsend ... wouldn't want to code that in c++
So I have been trying to make Custom Inspector. And now I have come to a problem, maybe one of you knows the answer to that problem.
So I want to create EditorGUILayout.MaskField() which represent my LayerMask. While I know how to set the label and the int, I am having trouble getting the string[] from my Layermask. How do I get that?
Hehe another way would be to do
public T GetValue<T>(int value) where T : Enum {
return Unsafe.As<int, T>(ref value);
}
Greatly reduces the line count and increases execution speed, but as the name suggests, screw up the programming and your whole process may break, or you get unexpected values
Unsafe.As is so fun to work with, you can dump the whole heap with it, cast something to something else that would never compile if it was made with a regular cast
I've known some Rust programmers who raved about how great the language is and they never have trouble getting stuff to compile... guess how they did that 😉
Rust 🤤
macros are by far the most useful thing i've learned in Rust
you can compress down like 400 lines of trait implementations into a single macro 😩
Let's say I have the 3D Model of a Dice. I want to take its textures, convert them to an mp4 and play it as a video texture in a no-texture version of the dice(a cube basically) in a way that will appear like the "normal" textured one. How can I do this ?
like, wrap the mp4 arround the cube in way that will closely resemble the dice textured one.
Not quite sure what you mean. How can you wrap a video file around a mesh..?😅
maybe by doing a hack on each frame of the video
I'm still not sure what you mean.
Is there like a video of the cube and you want to extract the texture that is used on that cube?
Hmm no. I need to rephrase a bit cause I got you confused. Give me a minute.
Why video? Is it an animated shader/material?
Nope. I just want to do it this way cause the size of a video(for video texturing) is far smaller than the individual sizes of each texture.
so I thought I could use a video to "fake" the textures of a 3d model
You only need 1 texture though. And I'm sure you can compress it to be less than a video.
fake like display it on a quad?
I simplified the use case. What if I have 100 objs with 100 4k .pngs ?
You want to change the quad texture to mimic a rotating cube?
Well, whatever you have, 100 4k pngs is gonna be better than a video containing the same pngs.
Sigh, I guess I have to re-examine what I want to do.
Thanks for your input though. It was invaluable.
I use string currentDir = System.IO.Directory.GetCurrentDirectory(); to get my current folder, but it does not work if there is a special character in the folder. Does anyone know how to fix this?
Can you elaborate on "does not work"? Does it throw an exception, is the returned path invalid? Also what's that invalid character?
it was a +
And I do not get anything in my array with the code:
string path = System.IO.Directory.GetCurrentDirectory();
DirectoryInfo di = new DirectoryInfo(path);
foreach (var fi in di.GetFiles("*.vrm", SearchOption.AllDirectories))
{
//Debug.Log(fi.FullName);
allVrmPath.Add(fi.FullName);
allVrmNames.Add(fi.Name);
// fi.FullName
//allVrmPath =
}```
It was a bug report and I did not have the time to transfer the project to a folder with a character in it yet, so couldnt debug it
And that works if there's no + in the path?
Seems like it works on my machine, with the + or not (Windows doesn't prevent it from being inserted into a file name or folder name)
hello
Yep, removing the + from the folder fixed it for him (full path was C:\Users\USER\Documents\ +Projects\STUDIONAME\PROJECTFOLDER)
Ahh it might have been de backslash combined with the plus
I see discord had issues with it
If you're using backslashes in a path you need to either use a verbatim string or escape each one:
var x = @"Path\To\Folder";
var x = "Path\\To\\Folder;
escape the escape character
But you can (and should) use Path.Join instead.
I did it
Thanks so much for all the help
Honestly It was mostly trial and error
Oh, you need to add a guard there to prevent a multi-select error
If you share code instead of an image I'll show you.
See #854851968446365696 for how to format code
You're going to get deleted if you paste it without a codeblock
weird
wont let me edit it
Nor delete it
public void myEnum <T>(SerializedProperty serializedProperty) where T : Enum
{
serializedProperty.enumValueIndex = (int)(object)(T) EditorGUILayout.EnumPopup(
(T)(object) serializedProperty.enumValueIndex, myEnumStyle());
}
ahh
public void myEnum <T>(SerializedProperty serializedProperty) where T : Enum
{
var next = (int)(T) EditorGUILayout.EnumPopup(
(T) serializedProperty.enumValueIndex, myEnumStyle());
if (next != serializedProperty.enumValueIndex) {
serializedProperty.enumValueIndex = next;
}
}
like this
Otherwise if you select multiple instances they'll all take the same value of the first one, even if you don't change the dropdown
It's a weird thing
It's just the way multi-select works
getting the value reads just the first selected, whereas writing it sets all.
thanks, let me try to replicate the error first so I can better Understand it
what do you mean by this "Otherwise if you select multiple instances they'll all take the same value of the first one, even if you don't change the dropdown"?
Cant seem to replicate it
let me take a short clip
Sorry, I am kind of a noob
If I understood it correctly, try setting the two objects to different values, then select both but don't change the value, and then select each individually again
and see if they still have their previous value
hm, idk then
I need some help, I am using Mathf.PerlinNoise to generate a noise map, when I input larger values into the seed of the perlin noise ||Mathf.PerlinNoise(seed.x,seed.y)|| I get some wierd results, like larger squares. This usually happens when the values get above 2,000,000. Is there a way to fix this, or do I just cap the seed at 999,999?
I'd cap the seed, I wouldn't work with 7+ digit numbers without a good reason
ok, that's a bummer. I might also look for some other noise solutions, custom ones
You're supposed to use a value between 0 and 1 afaik. Also it's not a seed, but position on the noise texture.
Also yeah, I don't think Mathf.PerlinNois-
ooohhhhh
Since I use GetCurrentDirectory() I ended up using the verbatim, thanks!
I have StreamReader with png data, is there any way to get that png open as a sprite without creating temp file?
How about mp3 or ogg as AudioClip?
At runtime?
You don't need to create a file. You can just read the stream into a buffer and pass it to a Texture2D
You can load a byte[] of PNG data
yes, runtime
I actually found that ImageConversion right after asking it
Read the complete stream into a byte[], then use the above.
but now problem is with audio
Audio I'm not sure.
yea, I got image working already
setdata is for raw wave data, but ogg is compressed
Somehow using this: https://docs.unity3d.com/ScriptReference/AudioClip-loadType.html
I'm not sure actually
I have idea for fallback using temp file and UnityWebRequestMultimedia, but that solution feels so uggly hack
Yeah, looks like that might be the only way.
Or you can use an ogg library that converts it to raw bytes
And use AudioClip.SetData
If you do go the file route you should write them here: https://docs.unity3d.com/ScriptReference/Application-temporaryCachePath.html
yea, I was thinking about this too, but didn't find any easy and simple solution for that, so probably using UnityWebRequest
You could try integrating this? https://github.com/NVorbis/NVorbis
Not all c# libs work with unity though
good point, I was planned to use persistent data and delete after use, but that is better.
I'd just go the file route though
Rather than wading out into the unknown
You can always replace it later
hey guys, not sure if this is advanced enough
I'm trying to find fast(er) alternatives to Poisson disk sampling to build a bunch of random point clouds
any keywords that would help googling would be a great help
rn it takes 1 second to generate 1 200x200 cloud which is terrible since I want to generate around 1000 and probably increase the size as well
and please correct me if I'm wrong, but I can't put it into jobs since allocating Random instances inside jobs will kill the performance
you can, you just gotta do it smartly
you can split the grid it into buckets and generate the stuff in parallel
here is a good article on such a thing https://medium.com/@1basudevpatel/faster-poisson-sampling-a76cb9a99825
this looks very interesting, thank you 👍
👍
I probably need to revisit jobs, as I had the idea of running multiple parallel jobs with the serial implementation. But I thought that passing non-blittable types (System.Random in this case) poorly affects performance 🤔
with buckets running in parallel there should be the similar limitation
this is something I need to revisit anyway though
I don't know if this is advance or general but what might a reason be for only getting an error from build an not when you play the project from the editor?
Knowing the exact error would help you and others determine this better.
Hya, quick question which I think might be more suited here in the advanced chat
I need to get references Inside my code to the InputActions I added to my Input Action Asset. I got a reference to the asset itself, but I cannot access the maps within the asset.
The docs are very unclear on how to do this
Im finding stuff like inputActionAsset.GetActionMap which doesnt exist etc. Anybody a clue?
inputActionAsset.actionMaps is an array, but it's always empty
Sorry, and you're using a callback model?
Like, you've got your reference to the input actions, and you're subscribing to the event?
i think it's actionTriggered or something
(like with):
myActionMap.actionTriggered += myHandler;
public void myHandler(... i forget .. some context parameter thing ...) { ... do your handling ... }
Hya. No not really. So far I've been using seperate Input Actions, enabling them one by one, etc. Now I want to use InputActionMaps and Assets. So I've build an asset, added a map and some actions, but I cant seem to figure out how to reference those maps (and therefore also the actions)
So from ActionAsset to ActionMap is the problem
I think I'll be able to handle subscribing and such once I can get acces to them
ok so you have an actionMap - you'll need to subscribe to the callbacks that it fires when it receives those actions
maybe I'm not understanding your question...
Yes, actionMap is in the action asset
So I got a ref to the ActionAsset, public InputActionAsset playerControls;
But, I cant get to the map inside the asset. playerControls.actionMaps.Count is always 0, and the script reference on how to do it is very scarce
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/ActionAssets.html#creating-input-action-assets you went through that already?
So I had assumed that, with 1 map added to the asset, to acces that would just be playerControls.actionMaps[0]. something, but that always fails
I haven't used this in a while TBH.. but I seem to recall it worked pretty well out of the box. Maybe the generate-code feature will help you get started?
yeah i've been stuck on those pages for an hour now lol
Also tried generate code, no luck. It doesnt really do that much in the first place tbh
Hm.. I don't know off the top of my head, sorry..
No prob, i already appreciate the attempt to help 🙂
I mean, also ensure that you save your PlayerControls object - i see a * there - dunno if that's the issue, but I saw a sentence that said the input maps aren't saved alongside the scene
PFFFF thanks hahahha
that was it
tiny little Save Asset button at the top
Yeah, playerControls.actionMaps.Count is now 1
auto generated code now also makes sense, now that its Actually adding stuff haha
.... a word file? yeah, no
I suppose..? I mean, just saying, posting a word file in a discord isn't a great idea for a variety of reasons
you're asking people to trust your file which might have malicious macros, you're trusting people with potentially embedded personal information, you're requiring that people use windows/word.. etc
you color coded it too..? 😛
haha true
yea I color coded it haha
This.. explanation? question? commentary? is .. scatterbrained.. I don't have any context for what you're asking or telling me
does my explanation make sense?
coz honestly I used pattern recognition and trial and error to make the code work and I want to understand it
I don't even know what you're trying to achieve or what your problem is...?
(and I'm trying to understand it but you're burying me/us in details that you're not explaining)
I refactored code A into Code B
Instead of making a grid with pixels like this, is there a way I can make it so the player can edit it in the game?
Why? what's code A trying to do? why'd you refactor it? etc
@late solstice Absolutely, but this isn't an advanced-code question. It's more of a design question or .. #💻┃code-beginner question.
//From this
DataMode.enumValueIndex = (int) (SearchIntegrationWithTMP.DataMode) EditorGUILayout.EnumPopup(
(SearchIntegrationWithTMP.DataMode) DataMode.enumValueIndex, myEnumStyle());
//To this
myEnum<SearchIntegrationWithTMP.DataMode>(DataMode);
Thanks sorry for putting it here I didn’t know where else
I call it many times so I shortened it
NP. If you don't know, though, it's probably in #💻┃code-beginner 🙂 You'll have to figure out what you're trying to do, though, before you ask. Do you want 100 buttons that the user can click and it edits your matrix? Do you have an image that they can click? etc - your question is too broad as it is
Like a grid, where the person can place pixels and remove pixels, im trying to make conways game of life.
many ways to do this, you can use GUI buttons for one
each button representing a specific index
Thanks, ill try to find a tutorial or something
@fervent parcel why are you casting your enum to an int anyway?
Why not just...... use the enum
like I'm trying to wrap my head around why you're doing all this double casting as some sort of ... Adapter pattern, and don't understand
Anywhere in your codebase that you're using Enums, use Enums (unless there is a specific reason to translate them to/from ints)
can you show me a workable example, I mean I would love to shorten it but failed
I mean, tell me what you're using your enums for and I'll show you..
I can show you mine, but they .. are .. I dunno, enums are kind of a core concept
My application is different than yours
right so, show me the code that switches the gui
I hope you're not doing something like...
if (displaymode == 1) ...
else if (displaymode == 2) ...
this
both examples work
first one is how I normally do it
i mean, how are selecting what to display, in the editor
where do you consume the enum value selected by the user
maybe paste the entire editor script into pastebin.com
this is a unity editor function
EditorGUILayout.EnumPopup
yes, i know.. and i know what it does
Paste your script. 🙂
Because your call to EnumPopup() should look more like:
public DataMode userDataMode; //somewhere in your declarations
...
userDataMode = EditorGUILayout.EnumPopup(DataMode.default, myEnumStyle);
Not sure I am allowed to, I am just updating the way this asset inspector looks, this is actualy an asset on the asset store
so I am doing it for a company called smitesoft
well... you're doing something.. odd (or potentially wrong) and.. my sense is that there's something fundamental you aren't understanding about enums
yes this works unless you use serializedProperties
you're treating them as ints - and they are, internally, but that should be opaque to you - you should be treating it as the value
what doesn't work about it?
SerializedProperties support enums just fine
including friendly display names, etc
if it worked, I would have done it
or maybe I made a mistake
but if you can give me an example to try so I know
coz I been at this for 2 days lool
I swear I tried every combination I can think of
this is what I'm trying [hard] to figure out, but it's hard without code or specific errors or .. what you're trying to achieve :p
I mean, enums are just... enums, you don't (in general) treat them as ints
I am just changing the style of enum typed serialized property
public enum DayType
{
Monday, // <-- don't treat this as "0", treat is as "DayType.Monday"
Tuesday,
}
Also, no one here is going to take/steal your code (maybe they are, I dunno?) they're just interested in helping. Parse out the useful bits if you need to. Additionally, if you're just changing the style, then I'm assuming all you want to be doing is passing a different myEnumStyle to the method..
its not my code
I dont care if it was mine lol
this script is 3k lines and I am just trying to change the style of it
I would have to ask them, but we are on different time zones
public enum MissionStateType // here's an example. I have a state Enum for "missions". Here's the declaration...
{
Awarded,
Started,
Complete
}
// and elsewhere in the codebase, where I display an object that needs this value:
if (CurrentState == MissionStateType.Started)
{
ActiveMissionPanel.SetActive(true);
NoMissionPanel.SetActive(false);
InProgressControls.SetActive(true);
PendingControls.SetActive(false);
CompleteControls.SetActive(false);
}
I don't do "if CurrentState == 1" or something like that
ok
And also, CurrentState is a "MissionStateType", not an int, so I never have to try to ... cast it back and forth to an int
but in this editor script
everything is a serialized property
its not an explicit type
I understand.. but I don't think you're understanding my question... wherever you consume the enum, you're .. doing something funny, but I don't know what since you won't show the code. 🙂
(It might not be your fault, maybe it's someone else in the company, but... just saying, there's something fundamentally wrong with your code/approach above)
gotta run sorry!
the editor script is only changing selected enum, they consume the code in the target script and I dont need to deal with that part
well thanks for the help!
but this code only changes the selected state of the enum, I dont know why you care what they do once they change their states, it doesnt changed the posed question
and the selected state, its the selected state in the inspector
Hey guys, I probably dont belong in this chat, but the guys on beginner code told me to take it here, I got some issues returning a value from a cell in a mysql table into unity, anyone willing to help?
you're being helped there.. I dont know why you posted your question there anyway. now you're just crossposting
what should I use interfaces for?
Youtube it or google it
i mean it should be your first instinct to google smtn lol
although that's for java
but who cares
Oh they crossposted. They were answered in general
hi guys i wrote a turret controller script and it has done its job great
now when i wanted to make an UI for it i have found a quite a bit of slop in it
my turretscript is basically not accurate enough or im screwin something up math wise when aiming the cannon at a point
basically what ends up happening is that the turret should rotate until the difference between its forward vector(red vector) and the reference vector(green vector) is 0 (then they should be the same)
but they are not, my turret stops a little earlyer than needed
https://paste.myst.rs/e7p88d40
and i dont know why,so feedback and tips on what am i doing wrong would be appreciated.
a powerful website for storing and sharing text and code snippets. completely free and open source.
visual representation of the bug (output of Debug.DrawRays in PointAtTargetPoint())
I'm on mobile, so it's hard to read the code well, but I noticed that in PointAtTargetPoint you use Turret.transform.position instead of Canon.position for setting one of the vectors.
@pale juniper first thing first - you have a really sloppy coding style so it's making this hard to read/understand, so you really ought to spend a little bit of time cleaning up your codebase so things like this aren't problematic (for you!) in the future.
Specifically: Name your methods with verbs, and name them clearly what they are supposed to do. What is turretcontrol() doing?? I can't tell what your intent is from the method name alone (and in the future when you forget your own codebase - and you will - this might not be obvious to yourself). Is it aiming the turret (AimTurret())? Changing some aspect of the turret (SetTurretControlMode())? Moving the turret's aim direction toward some direction (RotateTurretOneTick())? It's hard to figure out what the problem is when we/I/you can't tell your intent from the naming convention. If you find yourself naming things like AimTurretThenRotateItThenSetTheAimMode() then you know you have methods that are doing too much, and bugs are going to be nightmarish to figure out).
Now on to the bug/issue itself - Without diving into your source code too deeply, I suspect that you've got the wrong location of one of your objects - double check your pivot/anchor/etc on the Cannon and Turret objects are .. correct - at least the same
You're also doing some.. stuff that I don't quite understand with your offsets:
actualcamtransform = wgcam.camtransform;
aimCorrectionfromcamera = actualcamtransform.InverseTransformPoint(transform.position).x;
offsetforturrets = wgcam.offsetforturrets;
aimpointdistace = wgcam.aimpointdistace;
Is it possible to get referece to button that was pressed by script thats attached as unity action on button?
EventSystem.current.currentSelectedGameObject thats work for me 😛
Quaternion.FromToRotation(Vector3.up, C.normalized);
Can also just set transform.forward etc. to C
ah, I didn't know that was settable
wait, how can that make sense
I think it is like transform.rotation = Quaternion.LookRotation(value)
there's not a unique rotation that sets a forward vector, but I guess it could just do the same thing as FromToRotation
ah, so it works correctly if up is used
But yeah, it's a handy shortcut
Please, can anyone help me? How can I check if the player went to the site that a premium link shortener sends?
That would be a question for your premium link shortener provider.
They should provide analytics. bit.ly does
Most likely it would be something like this: https://link.shortener/link-id?id=your-unique-user-id
hi, i dont know where to post this but my unity froze when i pressed play and i didnt save in unity so i cant shut my pc down
you can save your scripts but any scene changes will probably be lost
what scripts have you written that could freeze unity?
nothing big tbh
the last script i edited before the crash is nothing i havent done before
public float travelSpeed;
// Update is called once per frame
void Update()
{
while(true)
{
transform.Translate(Vector3.right * travelSpeed * Time.deltaTime);
}
}
yikes
a while true will run infinitely
thats what i want
yes but you've done it in update
and unity runs each frame on each mono sequentially
meaning you've halted the entire program
oh...
if you want a while loop look into coroutines and yield return's
https://docs.unity3d.com/Manual/Coroutines.html
ive never understood how these things actually work, i really should tho
thanks
hello
I'm struggling to understand how I'm supposed to use state machines
our game is story driven and it starts off with some gameplay and cutscenes
who says you are supposed to use state machines? its certainly a good idea in places but there is no fixed rule... generally what you probably want is divide a system into mutually exclusive states to make transitions between those more explicit in a single place, in code. so for example you could have an init, menu, inventory, game, cutscene, death, gameover, ... state in your game manager and define what has to happen onEntry/Exit of those states and which from-to transition are allowed... a properly designed state machine would allow you to expressively define those transitions and actions and avoid most or all if/else or switch statements
beacuse they seem like they would make coding puzzles and everything a lot easier
I could trigger stuff based on a state
like, cameras for cinematics and stuff
you know?
yes, thats the point
so that's why I wanna use them, because they're simple to set up in my project so yeah
hmm
what is the question then? if you know what they are good for...
this is a multiplayer game so it's more complicated
I just need to know how to not under and over use them
do I use them for a lot of things like walking, running, jumping, shooting, reloading, what tab you have open in the inventory and settings menu
etc.
that really depends on the ceremony your FSM(s) require to be set up... if it makes code longer or more complicated or the thing isn't really a system... maybe not use them?
let's say I have the game start of as a cutscene, then change gameplay where the players can move, then short panning of the camera to attract the players' attention, more gameplay and then cinematic again
that would require
gameplay state
cinematic
and panning
Also if you have a lot of interdependent states that would cause state explosion... dont use them... hierarchical FSMs also get out of hand quickly. better use other models
and based on these I could enable and disable certain gameobjects
this would be the way to go, right?
that should probably two systems that interact via signals/events, not all one FSM
you shouldn't use a FSM for something a timeline can do
it's like, if I enter a trigger, then I want that to change the state to a cinematic or something
or in case I wanna make a puzzle and have certain states I need the player to progress through
I just feel like it's way more simple to use it this way
yes, you have a FSM that handles the main game-states like cinematic, play, menu .... but you don't define what happens in any particular cinematic in THAT FSM, you use other ones or other types of abstractions for the gameplay, the cinematic and the menu... so: don't create one huge FSM, make separate ones and have them stay on one level of abstraction/organization
I know
what would a good system for that look like
I just need like, let's say a trigger
when you enter it it triggers the cinematic state
and in that state I want the player to look at something or get switched to a different scene, whatever
how could I make that modular?
each trigger -> cinematic -> optional-action could be one such module. that action at the end could trigger the next state-transition.
I could make a unity trigger or something-
and use the cinematic state for other scripts to like
just have a base script that tells you "Ok, you need to disable the player and stuff"
which'll happen every time the cinematic state starts
and then switch back to gameplay or something
that should be defined in the fsm-state
yes
I know
I can also use this for reloading and shooting in case I need that to do something
that's not overusing it, right?
the system I'm using is just a an enum of states and functions that are like
NameOfState_Method
overuse happens when you feel you don't understand whats going on anymore... then you introduce abstractions
and I can make it a void or IEnumerator
I see
can you explain to me what you mean by abstractions just so I can make sure I understand it well
I'm kinda sleepy sorry
example: a FSM is an explicit abstraction over code that uses if/else/switch to express the idea of a "state"
basically you build a higher level system that orchestrates more localized/detailed/lower systems and only deals with the interactions between those at the higher level
I think I get it-
abstraction can also mean that you encapsulate and hide a modules inner workings such that other parts of the larger system only interact with it through a simple public interface
Thanks for your reply, you have revived my hopes. I'm going to ask bitly support and the shortener I was testing. Do you know other shorteners that allow you to check this in unity?
the problem is that I think bitly doesn't pay to go through my links. I'm looking for shorteners that give me money
I don't really understand what you're looking for. Sounds like you want an ad network.
I'm looking for a form of monetization that pays fast, I was blocked when I was about to withdraw the $100 and I don't want to risk going through it again
I haven't found ad networks with a low minimum payout, but link shorteners have several that pay when I get to $5
even if I pay little, it's worth it to me, when I'm earning more I'll use the ad networks
The secret is that the ad rates scale equally to the low minimum payouts 😛
CODE ORGANISATION QUESTION: In a big class I have lots of variants of ways to do things, as I determined how to do things in a complex little part of the project. Is it the done thing to duplicate the class with a version name, and prune it down to what's best, thereby keeping the original for reference/later consideration? Or do you simply clean up the original and discard all the various different ways iterated to eventual choices?
if you're refactoring it's best to retain the original yes
it may be bad but it works, and you'll probably need to reference it many times, even after you've finished refactoring it since issues can arise later on
i like to keep it in a separate folder in Unused Scripts for example and add Old at the beginning (you can even put it in a different namespace)
Do you not use version control, like Git?
i do yeah
but i don't want to rollback when i can just click on a file
whatever works
Most IDEs have a "compare with history" option, or you can look at the history on GitHub or wherever you host your repo.
Can somebody give me a proper explanation of this operator? =>
have you googled it and read the many sites that explain it?
It's just syntactic sugar for a delegate.
If that doesn't answer your question you're probs in the wrong room.
I kind of understand that
I understand using it like this void Start() => gameObject.SetActive(_active);
Depends on where it's used. It's also used for expression bodies, to avoid braces in single statement methods:
public void Log() => Debug.Log("Hello world");
But not like this SomeMethod(() => somethingElse);
It's creating a "first class" function that you can pass as an argument to another function as a callback.
yep
@native hinge https://www.tutorialsteacher.com/csharp/csharp-delegates
🤯
Funception
Not sure how that works but cool, thanks
To store references to functions in variables
Hello guys I am trying to swap 2D squares so that they are sorted according to their height. I am using bubble sort but the swapping is not correct. I suspect there are some wrong assumptions in how I swap my squares. Here is the code : https://hastepaste.com/view/gHKvaF0NB.
I posted this question in the beginner sections and 2D but no one answered it yet.
I already answered you in #💻┃code-beginner
or somewhere
I've lost track with all your crossposting
You don't need to write bubble sort
You can use List.Sort
Hi. I upgraded my Unity to 20.3.20 and VS to the latest preview and suddenly my Newtonsoft.Json NuGet package got unusable.. IntelliSense wants me to use "Plastic" (what is this?) and even tho i can rebuild the solution in VS, Unity Compiler won't let me do anything as it is still missing the assembly
Something to avoid, at all costs! Almost all syntactic sugar in C# should be avoided. Gross generalisation. But truth 😉
Huh?
Alright
@misty glade => makes a lambda function
The idea is to use all various sorts such as merged sort, bubble sort, radix sort and etc 🙂 I do this do visualise all the algorithms 😛 I agree that you have a solution but the meaning of the 2D algorithm visualiser is to show the various sorting algorithms 🙂 @kindred tusk
I know what it does, I use it every day. I'm curious about the advice not to use it.
I wrote one in the last ten minutes even..
isgServerProcess.ErrorDataReceived += (sender, args) => { if (args.Data.Trim().Length > 0) e(args.Data); }; //soak empty errors
The only time you should avoid it is in performance critical code that is run frequently (like Update()), because it allocates memory
That's fair, but .. still, I believe the syntactic sugar in C# to be one of it's greatest strengths
I find stuff like => and ternary operators kind of harm readability (and not to mention the => operator looks like a comparison at first glance)
I don't think => qualifies as syntactic sugar
Avoid delegates, virtuals, interfaces and Actions and Events. If you want fast and light. Syntactic sugar in C# is only a strength (at all) because the language is so old fashioned verbose.
uh
private static Person GetCrewMember(Battle b, bool C1, int index) => (C1, index, index) switch
{
(true, 1, _) => b.C1Crew1,
(true, 2, _) => b.C1Crew2,
(true, 3, _) => b.C1Crew3,
(false, 1, _) => b.C2Crew1,
(false, 2, _) => b.C2Crew2,
(false, 3, _) => b.C2Crew3,
(_, _, _) => null,
};
this would be like 30 lines of vertical vomit without this sugar
that's like 75% of the language
This is just .. terrible advice, sorry
I'd make a case that the explicitness of C# is its greatest strength, and the reason it's possible to use malloc and stackalloc within what is otherwise a messy OOP language.
These opinions are 🤯
that code seems to indicate some kind of bad design to begin with
The naming convention of "1" "2" and "3" is misleading - they should be named "front" "middle" and "back"
e.g. why are there are 6 variables instead of an array or list something
C1Crew1, C1Crew2, C1Crew3, etc.
In this game, crew members have a "position" that have domain-specific logic
Think of position 1 as the captain - they have some bonuses, special game logic, etc
So?
It's not a variable-length array/datastructure, etc
He's using tuples to generate a "truth" for a highly succinct but unreadable switch statement. I think.
you can use an array without it being variable length. Sometimes just to make the code easier to write
There's no reason to use an array here - the size of the data structure isn't variable, iterating over the array isn't something that happens, etc
You should always try to make things uniform
Arrays achieve uniformity
Uniformity means you don't need cookie cutter code like GetCrewMember
This is, for sure, a "denormalized" data structure, but it makes sense for this particular application
I bet you've ended up writing almost all of your code 6x over for each variable
so the code is 6x bigger than it needs to be
Er, no..?
well, that sometimes happens
Thank you very much for this. This is my tendency, as a result of decades of iterating in design software, and a lifetime of writing of C before that. Just wasn't sure if it was still a thing. Glad it is! THANK YOU!!!
although as mentioned later version control also achieves this
up to what you prefer
If I renamed the variables to something like this, this might make more sense:
private static Person GetCrewMember(Battle b, bool C1, PositionEnum position => (C1, position, position) switch
{
(true, PositionEnum.Captain, _) => b.C1CrewCaptain,
(true, PositionEnum.FirstOfficer, _) => b.C1CrewFirstOfficer,
(true, PositionEnum.Engineer, _) => b.C1CrewEngineer,
(false, PositionEnum.Captain, _) => b.C2CrewCaptain,
(false, PositionEnum.FirstOfficer, _) => b.C2CrewFirstOfficer,
(false, PositionEnum.Engineer, _) => b.C2CrewEngineer,
(_, _, _) => null,
};
I'm using version control but, like you, find it overkill (and a search nightmare) when trying to have a quick look at how I did something (an unknown time ago).
why do you use the index / position twice?
Looks like he's saving it for something else, spacer, at the moment.
Hard to explain in a nutshell but there's abilities that .. deflect the "active crew member" onto themselves
think "Taunt" in hearthstone
anyway, placeholder for the moment but it needs to be renamed for sure
anyway was just more commenting that this "simple" getter would be much larger vertically with a traditional if/else statement
@misty glade I think I get exactly what you're doing. Been down that road before.
I tend to (these days) use drop in state objects for this kind of thing, and call at them. And write verbose, so I don't need comments or my memory to work to understand what it does in 2 days time.
So where you're relying on => I'd wind up with a bunch of objects that descend from an abstract, each with the appropriate functions fleshed out.
a simple 2D array would make GetCrewMember 1 line, and it has the bonus that you could add additional roles and crews with a single line change.
suppose in the future you want 3 crew rotations instead of 2, or you add another role
anyway, I give up. Some people really like repetitive inefficient code.
there is a case to be made for engineering this "up" to be more extensible, but that's not on the radar in any near future
I hear what you're saying and don't disagree, but there's really no repetition in the codebase with respect to crew positions/etc
@stable spear you might undersstand what you mean, but until it's laid out, and provides the same insights and opportunities for expansion as tuples as state, it's difficult to comprehend how it's at all flexible in two arrays
But this is coming from someone that uses int4's for state, so ignore me!
I just sort of fundamentally believe that something like:
LeftPlayerCrew[1]
is more error-prone or less obvious than
LeftPlayerFirstOfficer
// or
LeftPlayer.FirstOfficer
You can use the enum as an index into the array
and obviously I could put some sort of thing internally
public RoleEnum FirstOfficer {get _Crew[1]; set;}
but I don't think that's the solution either
I haven't been following along so maybe ignore me, but isn't this just a dictionary with more steps?
@misty glade keep going with the (stateABC, stateXYZ, stateUVW) until its evolved and you realise the best other way to do it. Eventually the best way will reveal itself.
It's ok - the discussion was about c# syntactic sugar, I posted a code snippet, and the conversation veered into a code/architecture review of my snippet. 🙂
I'm pretty happy with my architecture as it stands.. I'd post some videos of gameplay but .. the developer art is embarassingly bad :]
I want to push towards state objects so that you can replace => with a . 😉
LOL, tbh I would expect no less for #archived-code-advanced, haha.
It's ok, I actually don't mind. "holy wars" are filled with strong opinions because.. those opinions come from people who have enough experience to make valid comments with experience to back it up. They're usually solid, too. The longer I write code and architect systems, the more I realize the less I know.
(and I've been doing it since about 1997)
(poorly, sometimes!)
I think the important bit once you know what The Right Way is to do something, when to break that and "denormalize" something, or when to unbreak it when you inherit some shitty codebase (and when that work isn't worth the payoff).
From my testing: Unity and C# can inline/optimise abstracts to almost as fast as direct calls, much more performantly than virtual calls (which Unity is slowly making a bit faster) and WAY faster than interface calls, which aren't optimised much, if at all.
if we‘re not ‚allowed‘ to use sugar/abstractions or lambdas and hide in terror from the GC, there is no point in using C# or unity.
my brain... hurts...
useSprint ? (Input.GetButton(sprintButtonName) ? walkSpeed * sprintMultiplier : walkSpeed) : walkSpeed
double ternary
🤯
Formatting is everything with nested ternaries
Could a ternary theoretically be endless?
Or is it limited to an amount of nested ternaries?
Probably limited, but likely sooner limited by confusion of the programmer
Ok
Yeah, I rarely use nested ternaries because they get sooo much harder to read then just one, or an if. At least imo.
they are an indication that the author doesn’t like other people much 😉
Very true. On rare occasion it will look okay, but the vast majority of the time it is better to just use an if statement.
I‘m waiting for n-ary in-line switch syntax with pattern matching C#8 🤙
why is RequireComponent(typeof(Rigidbody2D)) getting rid of the kinematic rigidbody and replacing it with a default one?
Quadruple ternary...
float speed = useWalk ? (useSprint ? (Input.GetButton(sprintButtonName) ? walkSpeed * sprintMultiplier : walkSpeed) : walkSpeed) : (useSprint ? walkSpeed * sprintMultiplier : 0f);
So confusing
But I also don't want 200 IFs
I mean it's nice to cram into one line, but this seems like it's going to be really hard to debug mentally..
Could you maybe do something like starting with 0f and adding a walkspeed or sprintspeed?
You're overcomplicating things. Ternary: Use Sprint && Get Button ? Sprint Speed : Walk Speed.
Use the && operator
float _speed = walkSpeed;
bool _useSprint = (useSprint || Input.GetButton(sprintButtonName));
if (_useSprint) _speed *= sprintMultiplier;
even simpler
I'm not quite sure if I'm replicating your logic above.. not sure what "useSprint" is, I'm assuming something that makes the player sprint even if they're not pressing the sprint button?