#archived-code-advanced

1 messages · Page 141 of 1

fast briar
#

One of my properties already have a Base Class which is MonoBehavior.

tropic lake
#

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

fast briar
#

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.

fast briar
tropic lake
#

cool

fast briar
#

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?

fresh salmon
#

Properties need a name, just like your filename field

#

You currently have access_mod type;, and you need access_mod type name;

fast briar
fresh salmon
#

I'm not sure what you mean here

#

That code seems correct

fast briar
#

Which is a child of another base class, Monobehavior.

#

Which CalculatedCollectedStars() is actually under.

fresh salmon
#

So you have a ClassA : MonoBehaviour, a DataExcel : ClassA, right?

fast briar
#

Yes.

fresh salmon
fast briar
#

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?

fresh salmon
#

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.

fast briar
#

Let me try.

fast briar
fresh salmon
#

You definitely can declare public abstract members -- are you getting a compiler error?

fast briar
#

Yes.

fresh salmon
#

What's the error message?

fast briar
fresh salmon
#

cannot be private, not must be private

fast briar
#

Ah, my mistake.

fresh salmon
#

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.

fast briar
fresh salmon
#

Not valid? Normally your override signature would be something like public override int CalculateCollectedStars()

#

Same return type, same parameters as the abstract declaration

fast briar
#

These are the errors im getting.

fresh salmon
#

Show the code of the method in DataExcel, it's originating from there

#

Looks like it's not marked abstract

fast briar
#

If i marked it abstract, another error happens, hold on.

#

Yeah, still errors.

fresh salmon
#

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
fast briar
fresh salmon
#

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

fast briar
#

I see.

#

Yeah whatever I do with CalculatedCollectedStars() nothing seems to work.

fresh salmon
#

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

fast briar
fresh salmon
#

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)

fast briar
#

Ive gotten this one now on.

fresh salmon
#

Yep, so in that class declare the override and provide your own implementation

fast briar
#

Gotcha.

#

After all of that, the CalculatedCollectedStars() still has the same errors.

fresh salmon
#

You need to post the error messages. It will be faster like that

fast briar
fresh salmon
#

Then post the updated code. There's still something that the compiler doesn't like

fast briar
#

Ive added the abstract unto the DataExcel also.

fresh salmon
#

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

fast briar
#

Give me a bit, for you to have a better picture ill give you the entire code through a code bin.

fresh salmon
#

Alright

fast briar
#

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.

fresh salmon
#

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

fast briar
fresh salmon
#

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

exotic basalt
#

How do I make a 12 hour timer that runs when the app is offline?

fast briar
#

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.

shadow seal
exotic basalt
#

What?

shadow seal
exotic basalt
#

I have and so far none of the ways work.

#

Oh sorry

shadow seal
#

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?

exotic basalt
#

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

fresh salmon
#

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

bleak gorge
#

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..
stable spear
#

@bleak gorge that sounds like offset is being calculated improperly?

regal olive
exotic basalt
#

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

buoyant lantern
#

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

dawn shard
#

what do you mean by over boundry? Like clipping through other objects? having a physical collider colide lettering with other objects?

buoyant lantern
#

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

dawn shard
#

ah like a paradox game?

buoyant lantern
#

Yeah.

#

Guess you could say that.

dawn shard
#

and the text needs to arc/curve squeeze to fit in an irregular shape

buoyant lantern
#

Correct

#

The shape being of course made up of provinces

#

Which are stored in the list

dawn shard
#

ok first stem is to compost the provinces together to some kind of 'mask' shape

buoyant lantern
#

I dont think I get what you mean

dawn shard
#

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

buoyant lantern
#

Yes, but I dont get what you mean by mask shape

dawn shard
#

ah well the shape of each individual province, you have it stored as something right?

buoyant lantern
#

Correct

dawn shard
#

you need to stictch all that together into one shape first, by 'mask' I meant the combined shape

buoyant lantern
#

Ah, I see

#

Well, how do I do that?

#

I cant just unite them into one gameobject

#

Thats the problem

dawn shard
#

depends on how you implemented the shapes

buoyant lantern
#

Right now it is literally just squares.

#

I havent modelled a map yet

dawn shard
#

how are they stored? the stitching together will be dependent on how they are defined

buoyant lantern
#

In a list

#

Inside of the country script

dawn shard
#

no I mean how is the shape defined

buoyant lantern
#

With colliders?

dawn shard
#

ok see the green blob in your example, that is a province correct?

buoyant lantern
#

A country

#

Made up of multiple little squares

#

Like I said no map yet

dawn shard
#

oh so the provinces are just squares, and you have a list of the indexes of provinces that are part of the country

buoyant lantern
#

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.)

dawn shard
#

ok well you could either write something simple now that assumes squares and then rewrite it when they change to other shapes

buoyant lantern
#

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?

dawn shard
#

don't worry about uniting the colliders, you only need to worry about uniting 2D shapes

buoyant lantern
#

But they are 3d.

#

So 3d shapes

dawn shard
#

but your text will be 2D right?

buoyant lantern
#

Yes

#

Just a normal world space canvas

#

Or whatever works best

dawn shard
#

also is this land? like is your 3D just for mountains/texture etc like in paradox games?

buoyant lantern
#

Yes

#

If i get what you mean

#

If you mean, is this a plane? then no, those are individual cubes

dawn shard
#

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?

buoyant lantern
#

Nono, it will be higher than terrain

#

so no problems there

#

and it also wont be transparent enough to get distorted or unreadable

dawn shard
#

ok then it's definitly simplifies the problem to think in just 2D, resolving the shape of a country into a 2D shape

buoyant lantern
#

yes

#

still too difficult for me though

dawn shard
#

Is your world something odd like a simulated sphere or is it the more traditional wrapped cylinder?

#

or even just a flat plane

buoyant lantern
#

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

dawn shard
#

like the game Asteroids?

buoyant lantern
#

I dont know what asteroids is

dawn shard
#

we call that a Torus world actually, if going off one side of the map takes you to the opposite side

buoyant lantern
#

I just remembered the term

#

Screen wrap

#

It simple screen wrapping

#

So, I guess torus world is the correct term

#

but Im not sure

dawn shard
#

dose going north cause you to apear on the south edge of the map? cause that's the key difference between torus and cylinder

buoyant lantern
#

Does it really matter

#

I havent decided on that yet

dawn shard
#

not really

buoyant lantern
#

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

dawn shard
#

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

buoyant lantern
#

Maybe I could use the existing country object which already holds the country script and stuff

dawn shard
#

that's a resonable place to put the code and store the resulting object

buoyant lantern
#

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

dawn shard
#

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

buoyant lantern
#

I see

#

Well, thanks for your help anyways

dawn shard
#

look your translating a 3D object into a 'shadow' aka a 2D silloute

buoyant lantern
#

Yes, yes

dawn shard
#

and for how to then composite these shadows together, this can be as simple as using a texture alpha value

buoyant lantern
#

okay

dawn shard
#

How tight fitting do the worlds need to be to the country? Is any overlap unacceptable?

buoyant lantern
#

They can overlap a little

dawn shard
#

like if their was a tiny little country inside of another

buoyant lantern
#

They could overlap

#

Definitlely

dawn shard
#

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?

buoyant lantern
#

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

#

?

dawn shard
#

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

buoyant lantern
#

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

dawn shard
#

If you had the countries shape defined, and then evaluaded each disconnected part seperatly to put a name in it

buoyant lantern
#

The shape is defined, my problemm is that it is seperate gameobjects that define it

dawn shard
#

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

buoyant lantern
#

That is a great idea

#

Thank you

dawn shard
#

you could even back up and rotate/bend the name to what ever degree you find acceptable to make it fit

buoyant lantern
#

Yep, that would probably be the best way

#

Now, making the 2d mask is the last thing in my way of good ui

dawn shard
#

Also you might want to try looking how Paradox games do their names, as they clearly figured out a solution for this problem

buoyant lantern
#

Yes, I know, but Clausewitz Code isnt really readable to me

#

Well, it is

#

But they handle everything way differently

dawn shard
#

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

buoyant lantern
#

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

dawn shard
#

2d shadows of 3d objects

#

or 'projections/shadows of 3d objects/colliders to 2D'

buoyant lantern
#

Yeah, the second one is giving me some good results

#

Thank you for your time

#

You were really helpful

dawn shard
#

your welcome, good luck, oh and out of curiosity where do you hail from?

buoyant lantern
#

Im german

dawn shard
#

your english was not an issue and I won't have know you weren't a native speaker if you hadn't said so

buoyant lantern
#

Well, thank you

#

I dont know if you are a native speaker, but in any case yours is also very fluent

dawn shard
#

my spelling on the other hand...

buoyant lantern
#

Is very good, what do you mean?

#

Except for some exceptions, like 3 (which can honestly happen to anyone), i barely noticed

dawn shard
#

well I'm just very bad at spelling generally, without spellchecking it will look terrible

buoyant lantern
#

Ok

#

Well, is it like dyslexia or just bad

dawn shard
#

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

buoyant lantern
#

That is true

leaden jungle
#

that's funny I want to do the opposite with a game project 3d into 2d 😛

exotic basalt
#

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

livid kraken
#

Current system time can not be trusted. Get your time from a trusted source @exotic basalt

flint sage
#

Doesn't really matter if it's an offline game

austere jewel
#

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

flint sage
#

You don't have much of a choice except to trust it if you've a local game

livid kraken
#

I once used a product that used system time to evaluate its 30 day free trial 😆

somber tendon
#

you can use worldtimeapi.org for development, not recommended for production as their faq says

flint sage
bleak gorge
hollow pollen
#

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?

compact ingot
flint sage
#

Custom

#

Eh, a php webserver can work fine

#

Lots of games probably still run on something like that

compact ingot
#

and the point was more about the REST/HTTP thing

stable spear
rocky atlas
#

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?

shadow seal
#

Randomly teleport, or set waypoints?

rocky atlas
#

randomly teleport on set locations

shadow seal
#

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

rocky atlas
#

ah

#

Wait, why an array of transforms. Why can't I just create a few empty GOs and then tp to them randomly?

tropic lake
#

yes emtpy gameobjects you can store them as type Transform

rocky atlas
#

ah, alright

woeful trout
#

How might one develop a coordinate system for tiles on a goldberg polyhedron (geosphere, hexsphere, there isn't really a catchier name)

dusky niche
#

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

tough tulip
dusky niche
#

and it happened randomly after building

novel wing
dusky niche
#

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

novel wing
#

you're probably using a package that depends on it

#

Entities for instance does depend on it

dusky niche
#

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();}

kindred tusk
#

Would inclusion of a package have any impact on your game if you're not using it?

dusky niche
#

its online so, im using playfab for user IDs and using mlapi

woeful trout
#

Okay, better question

#

Where can I go to get some insight into my first question?

dusky niche
#

my database is just a server side http to aws arurora DB

novel wing
#

Can't remember his exact name though unfortunately

woeful trout
#

Can you remember any key words he used in his post, so I can use the search function?

woeful trout
#

XD

novel wing
woeful trout
#

I'm not sure what I'm supposed to be looking at, but I to feel "omg, Unity" quite deeply

dusky niche
#

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

novel wing
#

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

carmine geode
#

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

urban warren
compact ingot
#

at some point, there are no more tutorials, basically if you ask in advanced code, tutorials are over.

dusky niche
#

Again, thanks to no one, i found the issue and fixed it. God seriously wonder sometimes what this discord is even good for..

carmine geode
#

oh ok i just thought that this question would go here as people didn't answered me on general

urban warren
compact ingot
carmine geode
urban warren
urban warren
carmine geode
#

ok thanks!!

gusty rivet
#

#if UNTIY_EDITOR is resolving as false even though I am not trying to make a build

#

how do I fix it?

devout hare
#

Did you typo it in the code as well?

tropic lake
#

UNTIY ?

plain sable
#

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

fresh salmon
#

Try storing the vector's hash code theVector.GetHashCode(). It's an integer value that, if well implemented, should be unique for each vector.

plain sable
fresh salmon
#

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

plain sable
#

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

fresh salmon
#

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

plain sable
#

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?

fresh salmon
#

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

plain sable
#

yup, I could probably just get away with a random int or something

fresh salmon
#

Reduces chances of collisions

plain sable
#

basically the biggest downfall of hashing

#

Well thanks for your input @fresh salmon , I think this gives me a decent place to start.

compact ingot
plain sable
#

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

fresh salmon
#

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

plain sable
#

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

fresh salmon
#

All good!

compact ingot
plain sable
compact ingot
#

Cause, unless you store that vec3 for future reference you are very likely to never find it again

plain sable
#

I think maybe I would need to get deterministic values using some sort of grid based system then

compact ingot
#

And if you use a grid, you can just use integer vectors

plain sable
#

because you are right

plain sable
#

because you are likely to return to the same grid

#

but not float vector

#

as you said

fresh salmon
plain sable
#

So I would generate a deterministic value for each grid?

#

maybe I can visualize my problem better for you

fresh salmon
#

And you could also use a HashSet<Vector3> or a Dictionary<Vector3, ?> to store the cached positions, and eventually some value linked to them

compact ingot
plain sable
#

let me mock up something

#

Imagine this simple road/path

compact ingot
#

For stored float vectors you‘d maybe do a nearest neighbor lookup…. For that you need a tree optimized for spatial lookup

plain sable
#

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

plain sable
compact ingot
compact ingot
plain sable
#

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.

fresh salmon
#

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

plain sable
#

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.

compact ingot
fresh salmon
#

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

plain sable
#

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

fresh salmon
#

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!

plain sable
fresh salmon
#

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

tulip edge
#

anybody good at checking 3d player movent scripts for me

gusty rivet
tepid dove
#
  • i have a generic Shooter<T> class that can spawn any projectile as long as T is a type of Projectile. 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.Action called AttackStartAction that gets invoked in OnEnable
  • 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?

long ivy
#

define an interface for Projectile that exposes the AttackStartAction, and use GetComponent on that interface instead

tepid dove
#

oh wtf you can do GetComponent on interfaces

wintry pawn
#

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!

untold moth
wintry pawn
#

I'm testing now with deep profiler to see better

untold moth
wintry pawn
#

deep profiler is not helping me a lot. still 10ms on this function when many sprite renderer are on screen

untold moth
wintry pawn
#

ouch, not good having 50% of cpu time on culling script when culling is not needed 😦

untold moth
#

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.

wintry pawn
untold moth
tired creek
#
    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?

sturdy edge
# tired creek ``` public float spawnDistance { get { return _spawnDistance; } ...
agile yoke
#

(Or write a custom editor if you deem it worth it, then you can do whatever)

tired creek
#

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?

agile yoke
#

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

sage radish
fervent parcel
#

hey guys, trying to refactor this but failing hard:

#

into something like this:

agile yoke
#

In the second image, try casting to T, not type

#

(and remove the type parameter entirely)

fresh salmon
#

You shouldn't be needing the type argument, just cast to T in the body

sage radish
#

And there's no reason to cast it from int to the enum type and back to int

tired creek
#
        get { return spawnDistance; }
        set {
            spawnDistance = value;
            Debug.Log(spawnDistance); 
        }
    }```
fresh salmon
#

That's a property

agile yoke
tired creek
fervent parcel
#

like this?

tired creek
fresh salmon
#

If you need to serialize the field, then serialize spawnDistance

sage radish
# tired creek Idk, doesnt show up

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.

agile yoke
#

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.

fresh salmon
#

Oh good spot, it's a stack overflow right here, got thrown off by the naming of the property

sage radish
agile yoke
# fervent parcel like this?

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

fresh salmon
#

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

fervent parcel
fresh salmon
#

That boxes the value, but should be only a minor performance drop

fervent parcel
#

but I still cant get it to work

fresh salmon
#

What's the error message? "Cannot convert int to T" right?

fervent parcel
#

yes

fresh salmon
#

There should be a workaround with Enum.GetValues to get a value by index

hasty hinge
#

JESUS IT JUST DONT WORK(wallruning

fresh salmon
# fervent parcel yes

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

fervent parcel
#

testing this:

#

I am just trial and erroring at this point

#

yup didnt work lol

fresh salmon
#

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

fervent parcel
#

looks good

#

testing it now

fresh salmon
#

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

fervent parcel
#

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

fresh salmon
#

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

blazing slate
#

why don't you just cast the enum ?

fresh salmon
#

Because it can't

#

return (T)val doesn't compile because enums are not always int

blazing slate
#

casting it to an object should work

#

like (T)(object)val

fresh salmon
#

Yeah I expressed it above and it works, then we got lost in all that

compact ingot
#

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++

solar otter
#

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?

fresh salmon
#

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

compact ingot
hollow garden
#

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 😩

pulsar isle
#

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.

untold moth
#

Not quite sure what you mean. How can you wrap a video file around a mesh..?😅

pulsar isle
#

maybe by doing a hack on each frame of the video

untold moth
#

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?

pulsar isle
#

Hmm no. I need to rephrase a bit cause I got you confused. Give me a minute.

sage radish
pulsar isle
#

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

untold moth
#

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?

pulsar isle
#

I simplified the use case. What if I have 100 objs with 100 4k .pngs ?

untold moth
#

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.

pulsar isle
#

Sigh, I guess I have to re-examine what I want to do.

#

Thanks for your input though. It was invaluable.

worthy lodge
#

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?

fresh salmon
#

Can you elaborate on "does not work"? Does it throw an exception, is the returned path invalid? Also what's that invalid character?

worthy lodge
#

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
fresh salmon
#

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)

hasty hinge
#

hello

worthy lodge
#

Ahh it might have been de backslash combined with the plus

#

I see discord had issues with it

kindred tusk
#

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;
modest lintel
#

escape the escape character

kindred tusk
#

But you can (and should) use Path.Join instead.

fervent parcel
#

Thanks so much for all the help

#

Honestly It was mostly trial and error

kindred tusk
#

If you share code instead of an image I'll show you.

#

You're going to get deleted if you paste it without a codeblock

fervent parcel
#

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());
    }
kindred tusk
#
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.

fervent parcel
#

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

agile yoke
#

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

fervent parcel
#

ok

#

Nop, no conflict

agile yoke
#

hm, idk then

mossy magnet
#

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?

lavish sail
mossy magnet
#

ok, that's a bummer. I might also look for some other noise solutions, custom ones

untold moth
lavish sail
#

Also yeah, I don't think Mathf.PerlinNois-

mossy magnet
#

ooohhhhh

worthy lodge
merry sonnet
#

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?

kindred tusk
#

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

merry sonnet
#

I actually found that ImageConversion right after asking it

kindred tusk
#

Read the complete stream into a byte[], then use the above.

merry sonnet
#

but now problem is with audio

kindred tusk
#

Audio I'm not sure.

merry sonnet
#

yea, I got image working already

kindred tusk
#

this maybe?

merry sonnet
#

setdata is for raw wave data, but ogg is compressed

merry sonnet
#

I have idea for fallback using temp file and UnityWebRequestMultimedia, but that solution feels so uggly hack

kindred tusk
#

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

merry sonnet
kindred tusk
#

Not all c# libs work with unity though

merry sonnet
kindred tusk
#

I'd just go the file route though

#

Rather than wading out into the unknown

#

You can always replace it later

merry sonnet
#

yea

#

thats true

#

thanks

rugged radish
#

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

hollow garden
#

you can split the grid it into buckets and generate the stuff in parallel

rugged radish
#

this looks very interesting, thank you 👍

hollow garden
#

👍

rugged radish
#

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

hollow pollen
#

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?

orchid marsh
#

Knowing the exact error would help you and others determine this better.

warm adder
#

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

misty glade
#

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 ... }
warm adder
#

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

misty glade
#

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...

warm adder
#

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

warm adder
#

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

misty glade
#

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?

warm adder
#

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

misty glade
#

Hm.. I don't know off the top of my head, sorry..

warm adder
#

No prob, i already appreciate the attempt to help 🙂

misty glade
#

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

warm adder
#

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

misty glade
#

.... a word file? yeah, no

fervent parcel
#

its how I write my notes 😄

#

want a picture?

misty glade
#

I suppose..? I mean, just saying, posting a word file in a discord isn't a great idea for a variety of reasons

fervent parcel
#

tell me if this makes any sense guys

misty glade
#

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..? 😛

fervent parcel
#

yea I color coded it haha

misty glade
#

This.. explanation? question? commentary? is .. scatterbrained.. I don't have any context for what you're asking or telling me

fervent parcel
#

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

misty glade
#

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)

fervent parcel
#

I refactored code A into Code B

late solstice
#

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?

misty glade
#

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.

fervent parcel
late solstice
fervent parcel
#

I call it many times so I shortened it

misty glade
late solstice
fervent parcel
#

each button representing a specific index

late solstice
misty glade
#

@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)

fervent parcel
#

can you show me a workable example, I mean I would love to shorten it but failed

misty glade
#

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

fervent parcel
#

just a custom editor enum

misty glade
#

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) ...
fervent parcel
#

both examples work

#

first one is how I normally do it

misty glade
#

i mean, how are selecting what to display, in the editor

#

where do you consume the enum value selected by the user

fervent parcel
#

this is a unity editor function
EditorGUILayout.EnumPopup

misty glade
#

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);
fervent parcel
#

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

misty glade
#

well... you're doing something.. odd (or potentially wrong) and.. my sense is that there's something fundamental you aren't understanding about enums

fervent parcel
misty glade
#

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

fervent parcel
#

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

misty glade
#

I mean, enums are just... enums, you don't (in general) treat them as ints

fervent parcel
#

I am just changing the style of enum typed serialized property

misty glade
#
public enum DayType 
{
  Monday, // <-- don't treat this as "0", treat is as "DayType.Monday"
  Tuesday, 
}
fervent parcel
#

yes

#

that makes sense

#

let me try again

#

brb

misty glade
fervent parcel
#

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

misty glade
#
    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

fervent parcel
#

ok

misty glade
#

And also, CurrentState is a "MissionStateType", not an int, so I never have to try to ... cast it back and forth to an int

fervent parcel
#

but in this editor script

#

everything is a serialized property

#

its not an explicit type

misty glade
#

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!

fervent parcel
#

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

jolly wave
#

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?

sturdy edge
hallow cove
#

what should I use interfaces for?

fervent parcel
hallow cove
#

bruh

#

bruh

hollow garden
#

i mean it should be your first instinct to google smtn lol

#

although that's for java

#

but who cares

sturdy edge
#

Oh they crossposted. They were answered in general

pale juniper
#

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.

#

visual representation of the bug (output of Debug.DrawRays in PointAtTargetPoint())

gray pulsar
misty glade
#

@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;
paper nimbus
#

Is it possible to get referece to button that was pressed by script thats attached as unity action on button?

paper nimbus
sly garden
#

Can anyone help please?

stable spear
kindred tusk
#

Can also just set transform.forward etc. to C

stable spear
#

wait, how can that make sense

kindred tusk
#

I think it is like transform.rotation = Quaternion.LookRotation(value)

stable spear
#

there's not a unique rotation that sets a forward vector, but I guess it could just do the same thing as FromToRotation

kindred tusk
#

It's just like LookAt with the second argument set to Vector3.up

#

I think?

stable spear
#

ok, but that's exactly what he doesn't want

#

Can transform.up be set?

stable spear
#

ah, so it works correctly if up is used

kindred tusk
#

But yeah, it's a handy shortcut

cunning dirge
#

Please, can anyone help me? How can I check if the player went to the site that a premium link shortener sends?

kindred tusk
#

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

gaunt gate
#

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

tropic lake
#

you can save your scripts but any scene changes will probably be lost

#

what scripts have you written that could freeze unity?

gaunt gate
#

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);
        } 
    }
tropic lake
#

a while true will run infinitely

gaunt gate
#

thats what i want

tropic lake
#

yes but you've done it in update

#

and unity runs each frame on each mono sequentially

#

meaning you've halted the entire program

gaunt gate
#

oh...

tropic lake
gaunt gate
#

ive never understood how these things actually work, i really should tho

hallow cove
#

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

compact ingot
# hallow cove I'm struggling to understand how I'm supposed to use state machines

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

hallow cove
#

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?

compact ingot
hallow cove
#

so that's why I wanna use them, because they're simple to set up in my project so yeah

#

hmm

compact ingot
#

what is the question then? if you know what they are good for...

hallow cove
#

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.

compact ingot
#

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?

hallow cove
#

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

compact ingot
#

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

hallow cove
#

and based on these I could enable and disable certain gameobjects

#

this would be the way to go, right?

compact ingot
hallow cove
#

uhhhhhhhhh

#

why tho?

#

I'm sorry, I learn from examples best so please bare with me

compact ingot
#

you shouldn't use a FSM for something a timeline can do

hallow cove
#

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

compact ingot
#

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

hallow cove
#

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?

compact ingot
#

each trigger -> cinematic -> optional-action could be one such module. that action at the end could trigger the next state-transition.

hallow cove
#

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

compact ingot
hallow cove
#

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

compact ingot
#

overuse happens when you feel you don't understand whats going on anymore... then you introduce abstractions

hallow cove
#

and I can make it a void or IEnumerator

hallow cove
#

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

compact ingot
#

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

hallow cove
#

I think I get it-

compact ingot
#

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

hallow cove
#

I see

#

thanks!

cunning dirge
#

the problem is that I think bitly doesn't pay to go through my links. I'm looking for shorteners that give me money

kindred tusk
cunning dirge
#

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

hushed fable
#

The secret is that the ad rates scale equally to the low minimum payouts 😛

ember geyser
#

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?

tropic lake
sage radish
tropic lake
#

i do yeah

#

but i don't want to rollback when i can just click on a file

#

whatever works

sage radish
#

Most IDEs have a "compare with history" option, or you can look at the history on GitHub or wherever you host your repo.

native hinge
#

Can somebody give me a proper explanation of this operator? =>

tropic lake
#

have you googled it and read the many sites that explain it?

native hinge
#

yes

#

But I still don't understand it

kindred tusk
#

If that doesn't answer your question you're probs in the wrong room.

native hinge
#

I kind of understand that

#

I understand using it like this void Start() => gameObject.SetActive(_active);

sage radish
#

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");
native hinge
#

But not like this SomeMethod(() => somethingElse);

kindred tusk
#

Ah, that's true.

kindred tusk
native hinge
#

Soooo

#

It's calling a function, and the function's argument is another function?

native hinge
#

🤯

kindred tusk
#

Funception

native hinge
#

Not sure how that works but cool, thanks

sage radish
#

To store references to functions in variables

regal olive
#

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.

kindred tusk
#

or somewhere

#

I've lost track with all your crossposting

#

You don't need to write bubble sort

#

You can use List.Sort

granite gust
#

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

ember geyser
misty glade
#

Huh?

native hinge
#

Alright

stable spear
#

@misty glade => makes a lambda function

regal olive
#

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

misty glade
#

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
stable spear
#

The only time you should avoid it is in performance critical code that is run frequently (like Update()), because it allocates memory

misty glade
#

That's fair, but .. still, I believe the syntactic sugar in C# to be one of it's greatest strengths

distant pivot
#

I find stuff like => and ternary operators kind of harm readability (and not to mention the => operator looks like a comparison at first glance)

stable spear
#

I don't think => qualifies as syntactic sugar

ember geyser
#

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.

stable spear
#

uh

misty glade
#
        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

stable spear
#

that's like 75% of the language

misty glade
ember geyser
#

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.

misty glade
#

These opinions are 🤯

stable spear
misty glade
#

The naming convention of "1" "2" and "3" is misleading - they should be named "front" "middle" and "back"

stable spear
#

e.g. why are there are 6 variables instead of an array or list something

#

C1Crew1, C1Crew2, C1Crew3, etc.

misty glade
#

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

stable spear
#

So?

misty glade
#

It's not a variable-length array/datastructure, etc

stable spear
#

all these variables have the same type, Person

#

so Person[] will hold them

ember geyser
#

He's using tuples to generate a "truth" for a highly succinct but unreadable switch statement. I think.

stable spear
#

you can use an array without it being variable length. Sometimes just to make the code easier to write

misty glade
#

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

stable spear
#

You should always try to make things uniform

#

Arrays achieve uniformity

#

Uniformity means you don't need cookie cutter code like GetCrewMember

misty glade
#

This is, for sure, a "denormalized" data structure, but it makes sense for this particular application

stable spear
#

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

misty glade
#

Er, no..?

stable spear
#

well, that sometimes happens

ember geyser
tropic lake
#

although as mentioned later version control also achieves this

#

up to what you prefer

misty glade
#

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,
        };
ember geyser
#

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).

stable spear
ember geyser
#

Looks like he's saving it for something else, spacer, at the moment.

misty glade
#

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

ember geyser
#

@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.

stable spear
#

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.

misty glade
#

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

ember geyser
#

@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!

misty glade
#

I just sort of fundamentally believe that something like:

LeftPlayerCrew[1]

is more error-prone or less obvious than

LeftPlayerFirstOfficer
// or
LeftPlayer.FirstOfficer
stable spear
#

You can use the enum as an index into the array

misty glade
#

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

urban warren
#

I haven't been following along so maybe ignore me, but isn't this just a dictionary with more steps?

ember geyser
#

@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.

misty glade
#

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 :]

ember geyser
#

I want to push towards state objects so that you can replace => with a . 😉

misty glade
#

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).

ember geyser
#

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.

compact ingot
#

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.

native hinge
#

my brain... hurts...

#
useSprint ? (Input.GetButton(sprintButtonName) ? walkSpeed * sprintMultiplier : walkSpeed) : walkSpeed
#

double ternary

#

🤯

compact ingot
native hinge
#

Could a ternary theoretically be endless?

#

Or is it limited to an amount of nested ternaries?

compact ingot
native hinge
#

Ok

urban warren
#

Yeah, I rarely use nested ternaries because they get sooo much harder to read then just one, or an if. At least imo.

compact ingot
urban warren
compact ingot
#

I‘m waiting for n-ary in-line switch syntax with pattern matching C#8 🤙

cedar ledge
#

why is RequireComponent(typeof(Rigidbody2D)) getting rid of the kinematic rigidbody and replacing it with a default one?

native hinge
#

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

misty glade
#

Could you maybe do something like starting with 0f and adding a walkspeed or sprintspeed?

orchid marsh
misty glade
#
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?