#archived-code-general

1 messages · Page 168 of 1

river sentinel
#

It's triggering a cast filter that should be ignoring the layer that the other object is on. The cast filter in question focuses on the Collision layer, but it's triggering when colliding with the player layer.

rancid sable
#

I remember getting this error in my project randomly without using any of those methods when I was working on using the gui system, try restarting the editor

marble swift
#

im not using the find statement. im kinda new. is there something else i have to watch out for.

dusk apex
#

That should be the case unless he's really working with Editor scripts

pure cliff
river sentinel
#

dunno. Only the players have rigidbody2ds.

pure cliff
river sentinel
#

and this is the physics2D settings:

dusk apex
hard viper
#

I want an interface to force anything that implements it to have a specific static method. is there a way to do that?

pure cliff
marble swift
pure cliff
dusk apex
pure cliff
pure cliff
#

holy shit brb I gotta go read about that one, thats zany

somber nacelle
#

it's how they implemented generic math. you can even overload operators with interfaces

river sentinel
#

so "all of them"

hard viper
pure cliff
#

what I really want them to add at some point is a Self constraint one day

hard viper
#

and yes, it does make sense for it to be static.

pure cliff
#

like

public interface ISomething
{
   public TSelf DoAThing<TSelf>()
       where TSelf : Self;
}
#

and literally all the Self constraint is, is that the generic is literally the thing itself

river sentinel
#

@pure cliff I've been called for dinner, can we continue this after in DMs? Sorry about this. ^^'

pure cliff
#

thread might be more appropriate

river sentinel
#

ah okay. I'll make one real quick

hard viper
#

not really. more like
public static int DoSomeMathSpecificToYourImplementation(int x, int y);

pure cliff
#

to build on above: then if you implement:

public class Something: ISomething
{
   public Something DoAThing() {
       
   }
}

would vaguely satisfy the conditions. Something roughly like that I hope exists one day

hard viper
#

can I use public static virtual? and override?

pure cliff
hard viper
# pure cliff whats the method you are trying to make

I have an electrical grid. Certain types of course parts will take in input for a direction they are getting electrified, and output a new set of directions to electrify, which will have ints for intensity assigned to it (like a big Vector4Int).

#

shit needs a static method. do not need an instance

river sentinel
#

CastFilter incorrectly triggering

pure cliff
hard viper
#

because it is going to be on a monobehaviour that does not need to be instantiated

#

if I have like a diode, I don't need an instance of a diode for the diode to tell me : if left, output right. If not left, ignore

#

that is tied to the definition of the class

somber nacelle
#

MonoBehaviour that does not need to be instantiated
well that can't possibly be correct

hard viper
#

and it should be

#

if I can make it static virtual, maybe that could work

somber nacelle
#

not possible. static methods cannot be overridden

pure cliff
#

strategy pattern

#

as it often always is XD

#

You're issue is you are trying to put this method on your class itself, but it has no need to be there

hard viper
#

well I have no need for it to be in an instance

pure cliff
#

You just need a single Dictionary<Thingy, ConductivityBehavior>

hard viper
#

you know, some of these functions are going to get big

pure cliff
#

A way to map between the two

hard viper
#

and each of these classes that implements this interface will need to be implementing other interfaces with more behaviours

pure cliff
#

what got you tripped up was that you wanted to put this static function on the class itself, but thats not necessary at all

hard viper
#

sir, if I make a capacitor script, I do not want definitions for what my capacitor does in 4 different files

pure cliff
#

just so I use the right lexicon, whats the class of your block thingies called

hard viper
#

TileMonobehaviour

solid quarry
#

bro nothing makes sense, I have a game object tagged, and yet there is no collision. My head hurts man

solid quarry
#

thanks

pure cliff
#

aight, so you basically want this:

public class ConductivityManager
{
    // Fill this however you need to
    private Dictionary<Type, ConductivityBehavior> BehaviorMappings { get; }

    public ConductivityBehavior For<TTile>() 
        where TTile: TileMonoBehavior
    {
        return BehaviorMappings[typeof(TTile)];
    }
}

@hard viper

#

And then ConductivityBehavior is just a readonly struct, and the really slick part is you can re-use em with params

#

Or even just have 1 single struct and its purely paramaterized

solid quarry
#

im fairly new to this so, as a student I want to be able to fully understand these code chunks before I absorb them into my games

pure cliff
#

And you just go

var behavior = ConductivityManager.For<MyConcreteTile>();
solid quarry
#

as of now this is what I have,

{
    public Rigidbody2D rb;
    public float jumpAmount = 10;
    public int jumpCounter = 2;

    public void Start()
    {
        jumpCounter = 2;
    }

    void OnCollisionEnter2D(Collision2D collision)
    {

        if (collision.gameObject.tag == "JB1")
        {
            Debug.Log("Jump Boost Obtained!");

            Destroy(collision.gameObject);

            jumpCounter++;


        }
    }

#

I have my item tagged aswell which is what confuses me

lean sail
somber nacelle
solid quarry
pure cliff
#

@somber nacelle I am also now realizing those static methods on interfaces mean that implementing strategy pattern will now be a little bit easier, as you can map the relation between Strategy <-> Consumer without needing instances of the Strategies up front, and can instead build the map first and then load the strategies on demand lazily, thats slick

hard viper
#

so abstract/virtual static members of interfaces were introduced in C#11

#

so they are supported. but not for us

#

I figured out a workaround. I can just give the base class TileMonobehaviour the static virtual method.

#

I could try the strategy pattern, which is what I originally wanted, but some of this stuff is going to grow really wild, so I need to keep each part more centralized. I will keep that in mind tho

pure cliff
hard viper
#

that class can have multiple methods in it

#

and I do not want the definitions to get very separated

pure cliff
#

You can put more than 1 method on your strategy

hard viper
#

again: I do not want to go to 4 different files to see the definitions of what a tile is supposed to do

steady moat
#

You can more than 1 strategy also

pure cliff
#

like for your FooTile, youd have a FooStrategy, and it would have 4 methods on that one FooStrategy class

steady moat
#

Also, you can create a custom editor if you want to centralize the serialization of different parameters.

hard viper
#

I have a tile SO with a bunch of flags for a tile. It can have a prefab associated with it, it can have a monobehaviour tied to it. and several situations need all 3

#

which is why I want to keep actual script tied to one tile to one class

steady moat
#

I do not see the issue there. Flags are flags. It can be a list.

hard viper
#

I'll need to think this over for a bit

steady moat
pure cliff
hard viper
#

the way he described it earlier was that I’d have a conductivity controller class which contains all definitions for all tile, which I am not doing

#

it could take references to functions. Having that map is ok.

pure cliff
#

Cuz I would say based on how complex your tiles are, I think you need to just get used to the practice of encapsulation and abstraction, it is not a bad thing at all for your 1 "thing" to be spread over multiple files, because that way usually leads to being able to re-use stuff and it means your principle "concepts" have been decoupled and encapsulated

hard viper
#

but I won’t make one mega file with all the functions for every tile in one scenario.

steady moat
#

Maybe you are generalizing before needing it ?

hard viper
#

i’ll need to read more on the strategy pattern

#

my game requires a lot of generalization

steady moat
#

If you do no need multiple strategy, you do not implement the strategy pattern

#

Otherwise, you spread over multiple files

steady moat
#

If so, you probably have overgeneralize.

#

It is like doing an interface for every interaction between classes

stone scaffold
#

hello

#

i require some assistance on my code

pure cliff
stone scaffold
#

basically i am making a 2D game, i wanted to implement a jump animation to my character so i tried two different ways

steady moat
#

If not, start there.

stone scaffold
#

yes but wait

#

one way worked fine, the other didnt, im not sure why the other one didnt work

#

i will post both the codes here

steady moat
#

No need for the working one

#

Also !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

stone scaffold
#

can i not send it as an image? it is small

steady moat
#

No.

fair jackal
#

It's funny that these channels are separated into code beginner, general, and advanced, since there are beginner questions in all channels

#

Just a thought

steady moat
#

True

stone scaffold
#

is that the right format?

steady moat
#

(However, most people that are above beginner are able to answer themselves)

stone scaffold
#

if this is the right format, then im not sure why this code doesnt work

steady moat
#

`

#

Use that instead

stone scaffold
#

oh

dusk apex
fair jackal
#

I think it's the slanted quote

stone scaffold
#
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);

        if (isGrounded)
        {
            if (Input.GetButtonDown("Jump"))
            {
                rb.velocity = new Vector2(rb.velocity.x, jumpForce);

                animator.SetBool("isJumping", true);
            }
            else
            {
                animator.SetBool("isJumping", false);
            }
        } ```
steady moat
#

Also, ask your question

stone scaffold
#

i see

#

yh so im not sure why this code doesnt work, when i run it, the jumping animations dont trigger

steady moat
#

Probably because you set the bool to false the next frame

pure cliff
#

basically, putting the breakpoint on this line:

if (Input.GetButtonDown("Jump"))
stone scaffold
#

i was hoping that by pressing the spacebar, it would trigger the animator to set the "isJumping" bool

#

but it doesnt

#

im not sure why

pure cliff
#

if you never hit the breakpoint, then you know isGrounded is always false for some reason and your logic is off there

stone scaffold
#

i see

toxic notch
#

I'm using the XR interaction toolkit and I'm trying to get the interactor that is grabbing the grabbable object. I have it wired to an interactable event on the grabbable but when I look at ActivateEvents args, I see I have a args.interactorObject but that's of type Interface IXRActivateInteractor. How do I just get the gameobject?

stone scaffold
pure cliff
#

is your breakpoint getting hit?

stone scaffold
#

ohhhh my god

#

i see now

#

i see the problem

#

yes my problem was the logic on that line

willow minnow
#

i feel so stupid, and i most likely am. Ive had visual studio, instead of visual code. im gonna die :/

somber nacelle
#

visual studio is better than vs code

willow minnow
#

OH, WOO

#

but it dosent have a stupid unity integration that i can tell, so im getting code

somber nacelle
#

!ide 👇

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

willow minnow
#

smexy

willow minnow
#

it still not work :(

somber nacelle
#

regenerate project files and restart visual studio. if that doesn't work, check the solution explorer and if the project shows there but is unloaded then right click and reload with dependencies (though theoretically restarting should do this)

willow minnow
#

it shows that it is loaded, but it dosent autofill

#

like i typed some keywords and none of them autofilled

somber nacelle
#

does it suggest anything or is it only not suggesting unity types?

willow minnow
#

it suggests stuff, not unity tho

somber nacelle
#

screenshot the entire IDE window, preferably with the solution explorer visible

willow minnow
somber nacelle
willow minnow
#

wait, something popped up

leaden ice
#

Miscellaneous files == not configured

willow minnow
#

shoot, one sec, something popped up to download, so im downloading that, but one second and it'll be mega restarted

#

ok, the donwload thingy worked, hurayy

languid crane
#

Recreating chess.

I have a class ExplorationResult that has two public fields,
public List<Vector2Int> ExploredGridPositionList;
public List<Piece> HitPieceList;

  • ExploreDirections() creates an ExplorationResult object and returns it.
    The ExploreDirections()is a general method and is potentially used for different usecases.

  • Each chess piece needs to know where it can move, and where it can attack. Piece internally uses ExploreDirections() to determine this information.

Now,
I need to store this information, If i store it in an ExplorationResult variable inside Piece, I can simply look at ExploredGridPositionList to know where it can move, and look at HitPieceList to know where it can attack.

My question is,
Does it make sense to use the same type for both usecases? I feel like it is not very readable when using it for the second case, but also does not make sense (For example, class MoveSet) to create the same exact class with a different name to hold the same data.
What do i do?

leaden ice
#

attacking and moving aren't really different things in chess

#

(yes pieces like Pawn can only move diagonally when attacking but that's ok)

#

basically - for each piece, calculate all the valid moves.

And if you're making an AI, then for all the valid moves for all the pieces, evaluate the board that would result, and pick the best position from those boards

#

that's the basic idea

languid crane
#

Although, you're probably right, i can still use that class for the explore method but store the legal moves in a simple list i suppose

leaden ice
#

as long as you recognize that a board location with an enemy piece on it is a valid place to move.

languid crane
#

no no, thats for a different usecase of that method

#

in another usecase, i just needed to get a list of all the pieces hit by the exploration

steady moat
#

A piece have a list of valid move. Those moves are either landing on an other piece or an empty space.

You want to know what pieces could be possibly be captured ?
You want to know what are the legal move of the current piece ?

untold shard
#

hello I'm something new, is there a way to imitate the grab, drop and throw objects from half life 2?

steady moat
nocturne sedge
#

ah

languid crane
# steady moat I fail to notice what are the two distinct use case.

So what im doing is, each turn, instead of calculating every single piece's possible moves, i only do it for pieces that are relevant.

  • To do this, I ExploreDirections() (all directions) from the piece that just moved (Both from it's old pos and new pos) and calculate the moves for the pieces returned by this method. First usecase.

  • But to calculate the actual moves, for each of the the pieces hit above, each piece explores appropriate directions (Eg. Bishop - diagonals) using the same method ExploreDirections() to find where it can move/attack. Second usecase.

steady moat
#

Why would you want to know the legal move of the piece that are being hit ?

languid crane
#

For example, consider this board

#

The bishop cannot move towards the bottom left direction because the pawn blocks

steady moat
#

To be honest, I would recalculate the whole board to reduce the possibility of error.

#

Each time it is needed

languid crane
#

But once the pawn moves, it can now move in that direction too, so its moves need to be recalculated

leaden ice
steady moat
#

Event base approach are risky

steady moat
#

In other words, I wouldnt cache the result. It does not seem to be that expensive to calculate.

languid crane
#

My thought process is, at the start of the game, all piece moves are precalculated and stored.
Whenever a piece moves, a few pieces now have new moves available, so only those pieces are recalculated and stored, and the rest already know their precalculated moveset

steady moat
#

Start by recalculating everything.

#

When it is needed

#

It will reduce the probably of incorporating bugs.

quartz folio
#

Chess programming is extremely well described, there is no need to innovate

languid crane
#

Thats fair, I will be trying to make this game multiplayer, so i'd like to have it optimized as much as i can, but not just that, i also see it as a personal exercise to try to write optimized code

#

If i ever encounter bugs with incorrect calculations, i can always switch to recalculating every piece's moves each turn or calculating when clicked on the piece or something, since i will only have to change when the calculation happens

steady moat
#

Also, preemptively optimizing is most of the time a bad idea.

#

You want to be able to mesure the impact of your change.

#

That being, said, there is also a minimum to do.

#

By minimum, I mean, do not allocate 3G of data on the ram without having any other alternative.

#

In that case, we can even say that it does not work.

hard mountain
#

Yes don't disregard performance completely

#

Stuff like proper data structures should be taken into consideration at all times imo

languid crane
#

I understand, i did start out with those three steps and ended up here. The only reason i optimized this is to challenge myself, with the assurance that if something goes wrong, reverting is extremely simple since only the when code needs to be changed, but all the calculation logic still remains the same

steady moat
#

Then, see how you can optimize it.

#

This way, you are "data oriented"

languid crane
#

I completely understand your point, but i'd still like to have my original question answered incase i run into it under completely different circumstances,

In the case where a data structure with the same data needs to be used for multiple different purposes, what do you do?

steady moat
languid crane
#

I am asking about the ExplorationResult class, not the ExploreDirections() method

warm aspen
steady moat
#

ExplorationResult is the result of ExploreDirections isnt ?

languid crane
#

yes

steady moat
#

Then, yes, it makes sense to use ExplorationResult in two context where you want to know about the result of the exploration.

languid crane
hard mountain
#

I'd make a separate class that stores the state in a static variable

#

There's also the scriptableobject route

steady moat
#

ScriptableObject wouldnt really fit here. We are talking about runtime data.

hard mountain
#

I use scriptableobject as data channel between classes a lot

steady moat
#

Also, the result is per piece I imagine, not really something you keep in static.

hard mountain
#

Hm

steady moat
#

We are talking about stocking the result of the research of a piece after ExploreDirections

hard mountain
#

Okay i misunderstood then

warm aspen
#

I'm struggling to understand the issue

hard mountain
warm aspen
#

in the original question you ask if it makes sense to use the same method "in both cases". What both cases? In the question I only understand one case: the piece trying to determine which spaces it can move to and which pieces it can attack

hard mountain
#

Even if the cases are different i see no issue with reusing the same class

#

It still represents the same data. So maybe just name your class better to reflect what it is (though this is obviously hard to do)

languid crane
languid crane
warm aspen
languid crane
#

I couldnt think of a situation where that's the case. The only possibility of that happening is knights, to counter that i'm just recalculating all knights every single move

warm aspen
#

I agree with @steady moat that I would just recalculate everything for every piece after every single move

warm aspen
languid crane
languid crane
warm aspen
#

his exploration might not hit some pieces that would be affected by his new position

languid crane
#

how?

#

Other pieces can only have new moves if

  • The old position was blocking moves
  • The new position now blocks moves
warm aspen
#

so if the piece that last moved frees a space for the other piece to move, how does the other piece know this unless it's hit by the first piece's exploration?

#

why try to optimize so much? A simple platforming game does more calculations than that every single frame, you would just do it once after every move

languid crane
warm aspen
#

oh, you explore from the old position and then again from the new position?

languid crane
#

yes, all the pieces hit from both those explorations are recalculated

warm aspen
#

Ok. Yeah, I see it. I still think it's overcomplicating something for almost no gain, but I understand now

west sparrow
#

I'm unsure why you are needing to calculate that. It would seem to me the only time a movement set matters, is when a piece is selected. So I'm unsure what the intent is myself...

languid crane
west sparrow
#

Unless it's for the AI maybe. Not judging just curious.

warm aspen
#

I was assuming it was for the AI

languid crane
#

Agreed, Its just that when i started out i didnt know how expensive exploring everytime was, so simply cacheing the moves and referring to the cached value made 'logical' sense. (Not talking about if it makes practical sense)

west sparrow
#

It is always good to challenge yourself, and definitely learning about pathing systems and methods can be valuable

languid crane
#

I probably wont be working on the ai, but since i already have all this optimized work done, i dont see how reverting would be better (unless there is a flaw in my design ofcourse), reverting to calculate ever time is simply just making it less optimized (however tiny the diffence is) for practically no benifit, i feel

west sparrow
#

I do agree it's over complicating it, however, you likely would cache all the available moves in a turn and then assess the best path for a possible strategy (for an AI). I'd probably recalculate every turn, but if you did only calculate the differences, it could be used to assess a risk to the AI strategy.

#

I.e. an AI could tell easier from incremental movements if a strategy is at risk. But if going down that path, I'd strongly recommend reading up on any existing methods for chess AI

#

For PvP, I'd only calculate available positions once a piece is selected, and maybe everyone once a piece is moved (although you probably dont need that data). And probably use Events and Delegates to create a message if a global refresh is needed. So it only runs the calculation when absolutely required.

But off the hop, I'd only calculate the movement options for a selected piece on selection, and leave it at that. You usually don't need to know any other pieces moves. Unless it is AI, I think.

warm aspen
#

or when he hovers over the space with the piece selected

west sparrow
warm aspen
#

although you could give some visual feedback to show which spaces are free to move or to attack

west sparrow
#

Yeah exactly

#

Great 🧠 think alike:D

crude mortar
#

but maybe you were referring to accessibility

torn eagle
#

Bit of a funky one but has anyone ever had issues with code running on a mac version of the editor but not windows?

#

My game runs completely different at home to on my work computer

hard mountain
#

I'm currently trying to detect which TMP_InputField was in focus after the user click on a button. The problem is clicking anything will reset all the input field's isFocused to false. What's the easiest way to work around this?

upper pilot
#

When I made apk for android, I set the aspect to 16:9, but my phone runs it at 20:9 since thats my aspect ratio.
But when testing with Unity Remote it uses 16:9 but the UI is squished.

My question is, how can I fix the issue so its not squished when resized to 16:9 and how can I force it to use 16:9 even if my phone is 20:9(like adding black bars maybe if needed or perhaps resize UI somehow to match.

Canvas scaler:
https://i.gyazo.com/2ac58139b85a437de04fc3239f02774f.png

hard mountain
#

you can test out how it looks in 20:9 in the editor

#

right here

upper pilot
#

yeah but I dont want apk to work only for 20:9

#

nor do I want to test it on all possible aspect ratios

#

is there a way to make it scale automatically without stretching

hard mountain
upper pilot
#

Tbh I assumed my phone is 16:9, not 20:9 😄

hard mountain
#

you can also experiement with the Match slider, i use 0 most often

upper pilot
#

Yes it was at 0 before.

#

canvas scaler is the issue I think

#

cuz it uses 1920x1080 which is 16:9

hard mountain
#

you do need the scaler though, otherwise your UI straight up won't work for different scren sizes

upper pilot
#

ah ok found it

#

Match Scale : 1

hard mountain
#

nice

upper pilot
#

Because I am running it in landscape mode

#

Not perfect, but it looks better

tired elk
#

Hi ! Since you can't directly put a ternary in a interpolated string ($"{condition ? resultA : resultB}") since : ends the interpolation, would having a first string that stores the ternary result then interpolate be lighter/better than having a string.Format ? Purely informational, I currently have a string.Format.

lean sail
tired elk
arctic tartan
#

Hi!
I'm trying to control the animation controller via script with a single blend tree that has all of the poses. Since I do everything via script, I'm using a direct blend tree with no transitions.
I noticed that values seem locked from 0 to 1 (both in the inspector and using animator.SetFloat()). Is there a way to set a negative value with direct blending (I'm using a generic rig, not a humanoid either)? The docs doesn't say anything about a limitation like this.

arctic tartan
foggy pasture
#

yo, is anyone aware of why i'd be getting this error

tired elk
# foggy pasture

What is the definition of Varyings ? Is it internal stuff ? It looks like it doesn't contain any uv field

foggy pasture
#

that's what i've been trying to figure out actually, it's a package so i'm trying to hunt it down

#

i don't know much about hlsl so i wasn't sure if it was a language thing

lean sail
tired elk
foggy pasture
#

right okay, ty

rich elbow
#

Hi, I'm using Invoke to call a function. It works on the Start void but not when it's inside my custom functions, is there any way to fix this?

hidden parrot
#

Code? That's not really very much to go off.

rich elbow
#

void HitPrefect()
{
scoreManager.noteScore = "Perfect!";
Invoke("setNoteHitToZero", 1.0f);
}

void setNoteHitToZero()
{
scoreManager.noteScore = " ";
}
(HitPerfect is called when a key is pressed)

vagrant blade
#

You need to show how you're calling HitPefect

hidden parrot
#

Yeah, that and please use nameof

vagrant blade
#

Also they're called functions, not voids

hidden parrot
rich elbow
#

i did and it is being called

hidden parrot
#

Can you use nameof, might fix it, might not

#

The other thing I can think of is the invoke is being interrupted somehow, like the script being disabled, gameobject being disabled, something stopping all invokes, etc.

rich elbow
#

Thank you!

topaz ocean
#

is there an effective way to prevent elements of a vector3 from growing to a NAN

fervent furnace
#

why it will become Nan?

topaz ocean
#

im manually computing collision forces and im facing an issue where an object forced into collision accumulates infinite velocity

fervent furnace
#

by sum(mv) before=sum(mv) after?

topaz ocean
#

I used to use a float velocity, I just checked "IsNan" but now its a vector3

knotty sun
#

so do the same on each component of the vector3

topaz ocean
#

Ah, okay, I was just wondering if there was a better way

knotty sun
#

clamp the x,y and z values to float.MaxValue

topaz ocean
#

nah that doesnt work if the value going in is a Nan

#

AKA exceeding infinity

#

I presume because by definition of Nan it doesnt know whether its past positive infinity, negative infinity, or whatever

fervent furnace
#

i just wonder why the velocity will becomes infinity, the mass is zero?

topaz ocean
#

no, its because I base the depenetration force on a factor of the velocity, so it scales exponentially

fervent furnace
#

(*((int*)&some float)&0x7f800000)==0x7f800000

knotty sun
#
Vector3 v3;
if (v3.x + someFloat == Single.Nan) v3.x = float.MaxValue;
fervent furnace
#

or float.isnan

topaz ocean
#

I did it a bit differently, I just used a temp variable and based the axis assignment on whether the result is an NaN

#

so if nan then keep the previous velocity on that axis

flat prawn
#

I need to deserialize json into a Dictionary<string, object>.
Googles MiniJSON can do this, but contains native code and can't be used in WebGL builds.
Unity.JSonUtility and Newtonsoft does not seem to be able to this.
Anyone know of a solution?

knotty sun
#

How did you serialize the json in the first place?

flat prawn
#

Using MiniJSON on a Desktop build. So yes I would like to solve the inverse case also, serialize a Dictionary. But is not as important

oblique spoke
#

Pretty sure Newtonsoft can

flat prawn
#

I think I could use Newtonsoft JsonConvert.DeserializeObject<Dictionary<string, object>>(json); and the recursively go through the result and convert any JObjects and JArrays I find....

knotty sun
#

It's really just a question of looking at the json produced by miniJson and emulating it for another library

#

i mean json is json but you do need to understand it

flat prawn
#

I would prefer not to write my own json parser 🙂

knotty sun
#

no need to write you own parser. but you do need to understand the json strings produced

flat prawn
#

Nothing strange about the json. The problem is that the working deserializers are tailored towards targeting objects with fields directly, and not create a Dictionary

knotty sun
#

so you make it a 2 stage operation

jade phoenix
#
    public IEnumerator FadeOut()
    {
        var timer = 0f;
        while (timer < 1f)
        {
            Debug.Log("fadeout");
            vignette.intensity.value = Mathf.Lerp(0.322f, 1f, easeOutQuint(timer));
            liftGammaGain.gamma.value = new Vector4(
                liftGammaGain.gamma.value.x,
                liftGammaGain.gamma.value.y,
                liftGammaGain.gamma.value.z,
                Mathf.Lerp(0f, -1f, easeOutQuint(timer)
            ));
            timer += Time.deltaTime;
            yield return null;
        }
    }```would anyone know why whenever i run this coroutine in one place, it works fine, but when i run it somewhere else it doesnt appear at all? the debug statements are being logged.
void remnant
#

What should I do when my vector is "too small" to be normalized. Is there a mathematical formula to normalize it by myself? I'm asking because .normalize returns zero

rocky helm
#

How do I correctly get all the vertices of triangles in a mesh (for simplicity lets say a cube) that look in the same direction as transform.forward? Right now, I have this code:```cs
public void CalculateFrontBounds(){
Mesh mesh = GetComponent<MeshFilter>().mesh;
int[] triangles = mesh.triangles;
Vector3[] vertices = mesh.vertices;
for(int i = 0; i < triangles.Length/3; i++){ //Loop through every triangle
int triangleStart = i*3;
Vector3 p0 = vertices[triangles[triangleStart]];
Vector3 p1 = vertices[triangles[triangleStart+1]];
Vector3 p2 = vertices[triangles[triangleStart+2]];
Vector3 triangleNorm = (Vector3.Cross(p1-p0, p2-p0)).normalized; //Get the normal of the triangle
if(triangleNorm == transform.forward){ //If the triangle is on the same plane as the forward facing face(s) is
AddNewPoint(p0); //Adds a new point if another point doesnt exist with the same position
AddNewPoint(p1);
AddNewPoint(p2);
}
}
}

Which, to me seems like it should work, but the problem is that ``if(triangleNorm == transform.forward)`` seems give me wrong results, but instead  ``if(triangleNorm == transform.up)`` gives me the vertices of triangles that look in the same direction as transform.forward, but even doing that doesn't work at all when I rotate the transform on the y or z axis.
#

Also, I noticed that mesh.vertices and mesh.triangles is 3x what they are supposed to be

#

Probably for like saving the uvs n stuff tho

rocky helm
hard viper
# pure cliff aight, so you basically want this: ``` public class ConductivityManager { //...

I looked into the strategy pattern, and I’m already using it. TileMonobehaviours are classes tied to my TileObjectBase SOs, which are listed in a big dictionary class which just holds a bunch of dictionaries to tie the different TileObjectBases to tiles. Once it gets to my ElectricalGridManager, it already has a reference to the TileObjectBase, which has a field corresponding to its TileMonobehaviour type. I just needed to make sure that the TileMonobehaviour implemented a function for the conductivity behaviour strategy IF the TileObject has a flag saying to expect it to have that function implemented.

#

This is why I was confused with your suggestion

steady moat
rocky helm
#

good point

#

I'll try to round it up here float point problems shouldn't happen

steady moat
#

You should just use the sqr magnitude

#

with an epsilon

rocky helm
steady moat
#

if((triangleNorm - transform.forward).sqrMagintude < 0.01f))

rocky helm
#

oh like that, k I'll try it

rocky helm
steady moat
#

Not exactly sure what is the idea of the function

#

However, you are correctly itering the vertices

proven path
#

When I have a class or component which only needs one implementation, is it still a good idea to derive this class from an interface for the sake of programming to an interface instead of an implementation?

rocky helm
#

Actually, I think I have an idea how to solve my problem, but if I just compare which point is closer to another point, then couldn't I do ```cs
Vector3 posOffset1 = targetPoint - point1;
Vector3 posOffset2 = targetPoint - point2;
float distance1 = Mathf.abs(posOffset1.x)+Mathf.abs(posOffset1.y)+Mathf.abs(posOffset1.z);
float distance2 = Mathf.abs(posOffset2.x)+Mathf.abs(posOffset2.y)+Mathf.abs(posOffset2.z);
if(distance1 < distance2){
blah blah blah
}

instead of comparing the sqrMagnitudes in terms of speed?
#

Like would this work, or is there a problem with this?

#

And if it would work, then would it be faster than sqrMagnitude?

steady moat
#

There is no need to actually do the sqrt here.

#

Also, your distance calculation is wrong.

#

distance = sqrt(posOffset1.xposOffset1.x + posOffset1.yposOffset1.y + posOffset1.z * posOffset1.z)

#

Also, there is no need for 3 points. Only 2

scarlet viper
#

Is it not possible for VSC colors and highlight to work properly when editing files from inside Packages folder ?

#

nvm i think i need to add assembly

steel finch
#

so I basically want to create a dungeon system for my 2d game with handcrafted rooms , can I use tilemaps to create each room prefab or would that be too inefficient

#

I'm asking this in the wrong chat aren't I 💀

primal wind
#

Tilemaps are for tiles

steel finch
#

interesting

#

So what is a good alternative then

primal wind
#

You could use it if your rooms are static but i guess they aren't so you'll have to make your own system

manic gulch
#

Hey there, I'm having an issue with animations right now
I've tried to add a new property to my animation clip, which is the sprite renderer of the "sprite" child object.

I've used EditorCurveBinding.PPtrCurve() to bind the property to the animation clip, more specifically this was the line of code that was being run

EditorCurveBinding.PPtrCurve("neph/sprite", typeof(SpriteRenderer), "m_Sprite")```

And yet it marks it as missing! Should I change `"m_Sprite"` or something?
manic gulch
pure cliff
# hard viper This is why I was confused with your suggestion

You use Strategy Pattern multiple times, its not a "one and done" sorta deal.

This is just another behavior/strategy if you will, "In what way does this electrify things" is yet another strategy to select.

Its quite common/normal to nest strategies in a tree, it forms a varient of a Behavior Tree effectively speaking.

Each time you hit a fork in the tree, that is strategy pattern, one is a subset of the other.

pure cliff
proven path
bleak thorn
#

How can I make it?

#

void Start()

#

void for all buttons

#

active selected color = green outline
sth like this

rigid island
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rocky helm
leaden ice
#

for the first version

#

but everything is pretty well described there

rocky helm
# leaden ice nothing

Then hy do I get this error? error CS0120: An object reference is required for the non-static field, method, or property 'Scene.GetRootGameObjects()'

leaden ice
#

because you are trying to call it statically

#

when it is not a static function

#

you need a Scene instance to call it on

#

"An object reference is required"...

rocky helm
leaden ice
#

whatever scene you want to get the root objects for

rocky helm
#

oh, I though that SceneManagement.Scene did that for me, but I guess not

leaden ice
#

SceneManagement.Scene is just the name of the type

#

you need an instance of that type

rigid island
bleak thorn
rigid island
floral coral
#
  • what are the things you include at the start of a C# script called? (the using blablah.blah;)
  • how can I make custom ones that work like a C++ library (as in, any script in the unity project can have using custom.name; and use functions from that like a C++ library)
bleak thorn
worldly hull
leaden ice
worldly hull
#

by default, only minimal libraries are included

leaden ice
#

If you want a "library" you make a .NET assembly or a Unity UPM package

floral coral
#

are there some tutorials for how to use them?

leaden ice
floral coral
worldly hull
#

normally i will just have few static classes to hold some custom extension functions for me to use lol

#

thats it, enough

leaden ice
#

it's very simple

#

they're more or less just part of the class name

floral coral
#

I'm overthinking it

#

I want something like the raycast function, where you write physics.raycast(...) and the raycast does something in the scene, but something custom for my game like output.send(...) which a circuit in the game would use to output data.

leaden ice
floral coral
#

and every circuit component would have a using GameNamespace.Output in order to access the function

stark sinew
floral coral
#

no, no, the code for communication is in the function, what I want to do is have an arbitrary script (like an extra one from a mod for the game) to have access to that function

ashen yoke
#

so the question is modding?

stark sinew
floral coral
#

yes

ashen yoke
#

in most cases where you want code mods support you use Harmony and expose some base class/interface for mods to extend from

#

modders will reference your game dlls in their project, access whatever they need, use harmony patches to modify code when needed

#

the only thing from you that is needed is some entry point, mod handling, and certain code style that simplifies modding

floral coral
#

I don't know how to explain well what I want to do, and I don't know if what you're suggesting is what I want to do.

stark sinew
#

If you want (code) modding support for your game, that's probably the fastest way

floral coral
#

I think what my ideal for this game would be is to have all of the circuits in the game be made the same way a modder would make them (like a json for definitions and a c# script for the functionality)

stark sinew
floral coral
floral coral
stark sinew
#

Ok, I begin to understand.

Why would you want to separate data and logic into separate file(format)s?
That's just making it harder I guess, most mods or add-ons may have a json or xml file coming with it, but those are mainly informational, things like the version and name.

Also, there are some different approaches to do this on your own, but I'd say they are not easy to execute

floral coral
#

a json is easier to read/write, and expandable

stark sinew
# floral coral a json is easier to read/write, and expandable

But then, strip the C# File completely and have the C# logic live in your Game

And make the Json file store a function name and an execution Style

So your game reads those form the json and knows "ok, I should call X function with Y parameters in Z style"

Execution Style being for example Update, OneShot etc

floral coral
#

I'm inspired by scrap mechanic, where the json file is used to define static "values" for a part (name, color, placement type, and script location), and a ||(lua)|| script that adds the functionality for a complex part in the game

#

and the lua script can use the scram mechanic api to interact with the game world

stark sinew
hybrid goblet
#

You could read into melon loader to make your game available for modding.
If you want to do it from scratch, this is gonna be hard

floral coral
stark sinew
floral coral
#

still off topic for what I want to do
I think*

stark sinew
#

It's not off-topic, you could do the same, include some kind of LUA Interpreter/Compiler in your game.

I think you're underestimating the work you need to do for modding support 😄

Options so far:

  • Use Harmony
  • Use MoonSharp
  • Create a SL from Scratch
  • Use a JSON that holds data about which function to execute with which arguments which would be handled by your Game

The last one would be the easiest as of now, if you understand the concept, but also the most limited.

Example of how Cities: Skylines did it
https://skylines.paradoxwikis.com/Modding_API
The game ships with a C# compiler which allows for automatic script compiling at game start.

#

Including a Interpreter or Compiler is the way, if you use a pre-existing one or create your own is up to you.

Even the JSON Approach would basically need some kind of Interpreter

fluid tapir
#

Hey there, does anyone know which IK solver does the Unity Two Bone IK use?

floral coral
#

on that note, Logic World (also made in unity) uses C# scripts for modded parts.
I know some sort of interpreter or compiler is needed.
I've observed that I pretty much always get stuck at how "things" communicate with each other (script with script, json to script, ...lua interpreter with script)

stark sinew
# floral coral on that note, Logic World (also made in unity) uses C# scripts for modded parts....

For a simple scenario, they wouldn't communicate with each other, your game would read the mod and understand what it says.

The mods could be limited to using only the pre-existing building blocks that your game provides.

Each building block would just be an ID and a function call that takes a variable count of parameters.

I'd love to give you a concrete example, but I'm on my phone and typing code on it s.... hard.

I'd advise you to fiddle around with writing a simple interpreter and VM from scratch, that'll deeply improve your understanding of the process that happens behind the scenes when you write and compile a script, it'll definitely help with understanding how Code Mods work.
It's not too hard, don't become intimidated!

floral coral
#

that's like writing visual scripting

#

Each building block would just be an ID and a function call that takes a variable count of parameters.

stark sinew
# floral coral that's like writing visual scripting

And? 1st, it's not, it's less flexible then Visual Scripting, but 2nd there are full blown good games out there that solely rely on Visual Scripting, so it's definitely good enough for modding..

Eventually you could start a thread to further talk about the modding "issue"

I'll give you an example for a pseudo JSON file

FunctionID: ModifyPlayerHealth
Parameters: 1
Execution: Update

or

FunctionID: 
CreateEnemy

Parameters:
GetRandomEnemy
GetRandomPosition

Execution: WorldLoad

of course 90% would be strings, it's JSON, you gotta interpret those strings and find out if they are meant to be functions or whatever else, basically you need to Tokenize the JSON into your own format before Interpreting it

FunctionID: AddCustomEnemy

Parameters:
myEnemySpritePath
someAttackValue
someSpeedValue
etc...

Execution: GameInit
floral coral
#

yeah, but then you have to add every function, and probably use all of them in the game.

In order to make something other people can use to create new stuff, you need to have some way to do extra computation, like math and control flow, so you would make a function for those, and then boom, you have a stupid json interpreter

stark sinew
#

If you don't want a stupid JSON interpreter, then utilize, as already stated, an existing solution like MoonSharp or Harmony, or create one from scratch.

I'm out, sorry, I've given enough information on the topic, not much more to say.

You'll get it done if you try, definitely, would be happy to see the results!

floral coral
#

Yes, I know, I already stated I know that.
I'm gonna dig further into moonsharp

pure cliff
#

@floral coral Lua is popular for C++ games, I know that, as there's a lot of solid "ready to use" libraries out there that effectively let you define a C++ function but then expose it as callable from a Lua wrapper.

Another option you can do for C# are plugins dlls, where the user must create a .dll of their own that meets specific criteria (has a specific method exposed on a specific class or etc), and then they drag and drop it into a specific folder and your game scans there looking for "recognized" .dlls that match the requirements.

gray mural
#

I have a game that allows player to create a levels and give them names. I save those levels into json file. What is the best way to call those json files? Just the name of the level that has to be unique, the name that is generated by custom ToJsonName method that deletes all spaces or int id?

swift falcon
#

Hello. I am using Addressables and it returns Asset as an "Object". Does boxing happens there since its a base class of Y?

public virtual Object Asset;
x.Asset as Y;

leaden ice
gray mural
leaden ice
leaden ice
gray mural
#

My nice level blabla => Mynicelevelblabla.json?

leaden ice
#

you would have to parse the json to get the level name in the scenario when the level name is part of the json.

#

if it's the filename then you just grab the filename

gray mural
leaden ice
#

I would probably also give them a .mygamelevel file extension for example too

leaden ice
#

for fun?

#

to identify them as level files for your game?

gray mural
#

well, they will be in specific folder

swift falcon
gray mural
#

Assets/#Levels/MyLevel.json

simple egret
#

Helps the user in avoiding drag-dropping completely random json files, if their extension is the same

gray mural
#

when you download a game, do you have an access to all scripts??

leaden ice
gray mural
#

wait, no

#

it doesn't matter

#

they won't have an access to file itself

#

they will be able just to view a level in the game

#

with already instantiated items

#

so it doesn't really matter

leaden ice
#

you don't want your players to be able to share level files with each other? You know they'll go looking for them

#

if you're saving them as json files they will be able to do this

simple egret
#

Yeah what's the point of a level editor and storing these in files if it's not possible to distribute them?

gray mural
#

like "share my level with foobar123"

leaden ice
#

sounds like a lot of work for you

#

you'll need a whole friend system, user login, authentication, etc

gray mural
#

well, I have done the basics already

leaden ice
#

and then users will still complain "Why can't I just give a level file to someone"

gray mural
gray mural
#

also I have created level system for the host for now

#

so no authentication rn

#

just levels that are created by host

#

But does it make sense to generate an id in format AvJ12SPfa3AN139SaP13Hy98 ?

quaint rock
#

well how do you want to generate the ID

#

it really should be some sort of checksum of the contnet

gray mural
#

and generate A-Z, a-z or 0-9

#

quite easy, right?

#

so it will be AvJ12SPfa3AN139SaP13Hy98.json

quaint rock
#

but why that instead of it being based on the real content

#

or using a established method of getting a globally unique id

quaint rock
#

like a SHA256 checksum or a GUID

#

depending on if you want it based on the content or just want a ID that will not clash with a other generated id

gray mural
quaint rock
#

i am talking about all the content

#

like the checksum would be for the entire contents of the file

gray mural
#

I will probably just create a method that creates a unique id

quaint rock
#

then would use the built in GUID then

gray mural
#

and the level should be found by its it..

gray mural
#

if I want just A-Z, 0-9

quaint rock
#

why do you need to control that, dont you just need a ID that never clashes

gray mural
quaint rock
#

ok and what happens when the same ID is generated twice

gray mural
quaint rock
#

ok so your intent is to check the database every time a ID is generated

gray mural
#
while (listOfAllIds.Contains(id))
    GenerateSmth();
quaint rock
#

and hope its never done concurrently

gray mural
#

also the chance for it to generate the same id among billions of combinations at the same second isn't that high

quaint rock
#

i am likly just thinking at the wrong scale, am used to dealing with databases that can get rather large

#

and where i would want to ensure the same thing is never stored more then needed

gray mural
#

well, I will do that without a database first

#

also thank you all for your help 😄

#

also 10 letters (A-Z or 0-9) is 3,656,158,440,062,976 combinations

#

pretty reliable

quaint rock
#

it might end up with things ids larger then you want, but this would be a nice way to always get the same ID from the same input file

public string CheckSum(string filePath) {
    using var sha256 = SHA256Managed.Create();
    using var fileStream = File.OpenRead(filePath);
    return Convert.ToBase64String(sha256.ComputeHash(fileStream));
}
gray mural
#

so if 8 billion people play this game, the limit of levels each person can create is 457,019

quaint rock
#

obviosuly could format in otherways that are not base64

quaint rock
#

why i mentioned it might get longer then you want

gray mural
quaint rock
#

its main advtange is, its gives the same ouput for the same input file

#

and can be used after the download to verify the contents are what was infact requested

gray mural
quaint rock
#

it would not compare the name, but the whole level

gray mural
pure cliff
#

if you are storing in a DB though, with a server, your database should handle what ID is assigned

#

when a player saves the level, the server will tell them what ID they were assigned by the database after it has been saved

wintry crescent
#

Hi, I have an object that has a script, and a trigger collider - and the script does not register callbacks. This is solved, when I add a kinematic rigidbody to the script. This is caused by the fact, that a parent object has a rigidbody, so all callbacks go to that object. Is there a way I can override this behaviour on a case-by-case basis without adding kinematic rigidbodies?

#

This is a work thing, and I'm forced to use a framework, and one of its features is that it turns all rigidbodies on certain objects into non-kinematic ones under certain conditions... it's more stupid than I can express with words, but I can't do much. It's how the system was made, it wasn't prepared for my usecase.

#

which is why I don't want to use rigidbodies

river sentinel
#

Trying this again, this time with a minimized project with only the integral details pertaining to my issue: I have a script which is triggering a cast filter on the incorrect object.

Player objects have a component called "TouchingDirections" which has three bools: IsGrounded, IsOnWall, and IsOnCeiling.
IsGrounded should be true when the player is touching the FloorColl layer.
IsOnWall and IsOnCeiling should only be when the player is touching the Collision layer.
Players touching other players should not be making any of the casts.

All objects colliding with the player are triggering all casts anyways.

wintry crescent
#

and, assuming you're using unity collider collisions what's your layer collision matrix?

river sentinel
#

oh whoops didn't mean to send that yet. I'm prepping a small project to show off the problem, one sec.

#

Scene: CollisionDebug (if the player objects are invisible just pop the Square sprite onto their child sprite renderers)

#

The physics2D settings should only allow collisions between Players and FloorColl, and Players and Collision. Not Players and Players. Yet for some reason, it is.

#

the weird part is I have another project where a similar script is used but this problem isn't a thing. And I don't know why that is.

#

You'll need to move the "players" via the editor btw

wintry crescent
river sentinel
#

there's two contactfilter2ds. groundFilter should only be checking the FloorColl layer and wallFilter should only be checking the Collision layer

#

if it's not then something went wrong when zipping but that's how it's set up on my end, so that's not the issue.

dark sparrow
#

Is there a way to blend the animations in a blendtree?
As you can see, its just changing direction instantly without smoothly transistioning

dark sparrow
#

That is also what I am using

wintry crescent
main shuttle
wintry crescent
dark sparrow
#

@main shuttle It does not look smooth, it just cuts to the new direction

river sentinel
#

thank you

wintry crescent
topaz ocean
#

is there a way to have a script-sided gameobejct? something that doesnt actually exist in the scene but I can assign components to?
I need to preserve transform axes of the object I have this script assigned to, so it would be helpful to be able to handle transforms in a nested object. I would prefer not to require an actual child gameobject for this script to function.

oblique narwhal
topaz ocean
#

if I also have a private collider can I assign that collider the private transform?

oblique narwhal
#

Well you can certainly have a private Collider or Collider2d as a member of a class.

Having both private Transform and a private Collider would not be the same relationship as if they were attached to a gameobject though.

#

Usually you would do something like:

`
public class MyGreatClass : MonoBehavior
{

private Transform myTransform;
private Collider myCollider;

public GameObject myPrefab;

private void Start()

{
var go = Instantiate(myPrefab);
myTransform = go.GetComponent<Transform>();
myCollider = go.GetComponent<Collider>();

}

}

`

topaz ocean
#

well I would like to orient a script collider with a script transform to use computePenetration on, I would have to add together the transform position and script transform though

willow minnow
#

i have few issues with my code, that i just dont understand how to fix. so one, the object that is tracing towards me needs to stop like 10 feet behind me, and im not sure how to do that, two, the object needs to start moving immediately, ive noticed it only starts moving whenever i stop moving, and three, i need a better way for the object to know im not looking at it. i was thinkin raycast but i havent seen any good way to do it online

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class CatController : MonoBehaviour
{
    public Transform target;

        [Range(0, 1f)]
        
        public float Range = 0.5f;
        [Range(0, 5f)]

        public float Speed = 5f;
  
        void Update()

        {

        transform.LookAt(new Vector3(target.position.x, transform.position.y, target.position.z));

        float viewGap = Vector3.Dot(transform.forward, target.forward);

        if (viewGap > Range)
            {
                transform.position = Vector3.MoveTowards(transform.position, target.position, Speed * Time.deltaTime);
            };
        }

}
oblique narwhal
oblique narwhal
willow minnow
#

doing that makes him move when im looking at him, instead of the opposite

oblique narwhal
#

Sorry had to adjust my code sample, I didnt adjust the variables inside the Distance check at first

willow minnow
#

now he moves the entire time

oblique narwhal
#

Depending on the size of the following object and the object that you are comparing it it might be that any movement at all easily falls in to your .5f range?

willow minnow
#

well, the object is a cat, and ill up the range, see what happens

#

so nothing happened, i up-ed the range, and the cat kept moving the whole time, and then i went back to the original script, and nothing changed

oblique narwhal
# willow minnow so nothing happened, i up-ed the range, and the cat kept moving the whole time, ...

So reading your code .. the pseudo code I would write for it (exposing the intent) is:

1: Look at the target
2: Calculate a "viewgap" which is the distance between the object and the target
3: if the distance between the target and object is greater than the specifie drange then move forward.

With that being said it seems to make sense (if the above check outs)

The only other thing I'm seeing as note is you might be mis-using Vector3.MoveTowards.

https://docs.unity3d.com/ScriptReference/Mathf.MoveTowards.html

The docs here are very weird - they are assigning the output to a currentStrength float, whereas you are assigning it directly to a transform.position . I'm not sure what the intended behavior here really is.

I'm not by any means sure that is your issue - but call it out because I don't understand what it should really be doing - so its at least worth looking at a bit?

#

I say this is weird because a transform.position is a Vector3 - but this function outputs a float.

#

So your assigning a float to a vector3 somehow - not sure what that does for movement - but maybe it does weird things and keeps moving?? 😄

simple egret
#

(you picked the wrong link - Mathf.MoveTowards does operate on floats, Vector3.MoveTowards on vectors, but they essentially do the same thing)

oblique narwhal
#

Then I retract my statement 😄 not sure what is going on - possibly some other behavior affecting whats going on??

willow minnow
#

for the little nudge, i think it might be something to do with the model and physic stuff

#

but it should be fixed if i can get the follow to stop a bit behind me, but i got 0 clue on how to get it to stop at a certain distance behind the player model

oblique narwhal
#

Well theres manual control and physics systems.

It looks like you are manually controlling it otherwise you'd be doing something like rigidbody.AddForce or such.

So in the manually controlling area .. I would think just stop telling it to move and it stops

willow minnow
#

i know, i can set it to stop. i just dont know how to set it to stop when it gets to a certain distance, but at the same time, i dont want it to stop behind a wall im next to just because its close to me actually

umbral agate
#

Respected, is it possible to stop the particle system immediately when user don't touch the screen..

turbid seal
#

Anyone knows how to fix the validition failed prblbm

willow minnow
sleek bough
#

@turbid seal Don't spam code channels.

turbid seal
#

K

turbid seal
willow minnow
#

run it as admin

simple egret
thin hollow
#

Is there a way to display an array of strings as an enum-like dropdown selection list in the editor window?
To be exact, I need a single string variable, that is displayed as a selection of a few specific options from an array of strings.
I have a list of item names that I want to choose from in the editor (Specifically in a node in a dialogue system(the image), that redirects the conversation flow depending on if player has or doesn't a certain item in their inventory).

Normally I'd just make a simple enum and be done with it, however, my list of items is being loaded from a file, and it is, naturally, expected to change during the game's development. Keeping enum in sync with it would be a pain, and leaving the parameter in the node be a string field (as it is now currently) opens possibility of bugs and errors due to typos.

leaden ice
swift falcon
#

Is there a way in unity for me to add to what happens when prefabs are made?

#

Like if I create a prefab could I have it create an SO in the same place and populate it with the data of the prefab?

#

Not been able to find anything but I think I found a way to add my own "Create Item from prefab" button in the context menu, so I can right click the prefab and then make the SO from it.

I will work on this for now but if anyone knows of a way to automate this on prefab creation, please let me know! Thanks 1Pikachulove

lunar kestrel
#

Does anyone know why when I put [SerializeField] and [Range()] on my privat variable, it doesn't keep the values after entering play mode? It seems like SerializeField doesn't work

somber nacelle
#

are you sure you aren't reassigning the values in Start or Awake?

lunar kestrel
#

[SerializeField] [Range(3,6)] private float number

lunar kestrel
unreal valley
#

Bunch them together with a Comma

#
[SerializeField, Range(3, 6)] private float number;
warm aspen
light rock
agile night
#

I was making some custom gravity modifiers to make the jump of my character feel nice. It works, however there is some funky stuff going on...

There are two gravity modifiers, one when the character is going up (jumpGravity) and another when the character is going down (fallGravity) If the character is standing still, there should be no gravity modifier (it would be set to 0)

#

But then, even when the character is not moving, the gravity modifier is set to fall gravity instead of 0 for some reason.

lean sail
agile night
agile night
lean sail
#

your character is likely just adding a ton of speed over and over, since your velocity would rarely hit exactly 0

#

think about the case where you are falling. your speed is negative, and in SetPhysics you are constantly adding gravityModifier * Time.fixedDeltaTIme
Regardless if its not moving because its stuck against an object, its still gonna add

agile night
#

aight, thankyu brother!

agile night
#

It's calculated automatically based on the desired height of the jump, and the time it should take to reach that height.

#

I should put a vertical speed limit tho

mossy valley
#

How do I make an animation for a UI element that can be used by any other UI element irrespective of their position. Cuz right now, whenever I try to make an animation, it uses their global position so all of the elements with that animation get thrown to the same position

Or is it better to just code the animations?

prime sinew
#

Ah, yes. Code the animation!!

mossy valley
#

Ahh okayy thank youu, will try DOTween

prime sinew
#

The documentation has examples too, so it's pretty easy to pick up

#

I suggest you get the hang of DoTween sequences. Very useful

steady egret
#

I just installed C# dev kit and Unity extensions to VS code and this error apppeared in my project. What can I do?

knotty sun
#

lol, an A: drive, haven't seen one of those for many a decade

steady egret
knotty sun
#

It probably does not matter in your case. I was just amused to see it

lusty dune
#

A: was the floppy drive iirc

tired elk
proper flume
#
void BuildMesh()
 {
     Mesh mesh = new Mesh();

     mesh.vertices = new Vector3[]
     {
         new Vector3(0, 0),
         new Vector3(0, 1),
         new Vector3(1, 1),
         new Vector3(1, 0),
     };

     mesh.triangles = new int[] { 0, 1, 2, 0, 2, 3 };

     GetComponent<MeshFilter>().mesh = mesh;
 }   ```
#

a square is supposed to appear but none appears help

hybrid goblet
proper flume
#

no

#

idk how

#

oh wait

hybrid goblet
#

you need to add a component called meshrenderer which has a material

hybrid goblet
#

to the gameobject which has you mesh creation script

proper flume
hybrid goblet
# proper flume still doesnt appear

https://www.youtube.com/watch?v=64NblGkAabk
Maybe this helps, he explains how to generate a mesh there, you don't need the procedural part if you want to do different things

Generate a landscape through code!

Check out Skillshare! http://skl.sh/brackeys11

This video is based on this greatwritten tutorial by Catlike Coding:
https://bit.ly/2Qd1o1d

● Perlin Noise: https://youtu.be/bG0uEXV6aHQ

● More on generating terrain: https://youtu.be/wbpMiKiSKm8

● Singleton: http://wiki.unity3d.com/index.php/Singleton

♥ ...

▶ Play video
tired elk
void remnant
#

What is better/More performant?

proper flume
lean sail
# void remnant What is better/More performant?

maybe delete that and write that R properly for ontrigger.
I also dont know what "where--" is but the one on the left only stores 1 list but accesses it through a reference (i assume). The one on the right stores a list per other class, and presumably uses an event to send that collider. If you're checking for performance in time, this is something you'll have to profile yourself or benchmark.
In terms of memory, its kinda obvious

#

oh those are brackets

void remnant
#

Sorry. So, on the left you have a manager class that stores every collider it interacts with and the dependent classes each filter the colliders they need. On the right you have a manager class that just fires an event, and the dependent classes each have a list where they can add the colliders they need through if statements. I'm more so asking what is better to use in the situation where there are a few tens of "other class" objects and one manager class. I don't know how Linq .Where() works. Maybe it's fast enough to call it on every onTrigger event. Because without .Where(), I will have to handle the storage and removal of colliders in each dependend class, which is annoying

lean sail
# void remnant Sorry. So, on the left you have a manager class that stores every collider it in...

it'd be worth profiling still if thats a concern. 10s of classes really isnt much.
You are looking at a time-memory tradeoff basically, do you want 50 classes each storing a list, or 50 classes to filter through a list.
If accessing the list a LOT, I would go with the one on the right, where you filter if you should add a collider as you get them. If rarely accessing the list, id go with the one on the left

void remnant
#

alright thanks. Imma do the left implementation because I'm lazy. If my potato laptop will lag, then I will have to do the right one

upper pilot
#

When I generate a script in c# it was able to figure out the return type.
Was it luck?
Now that I try it again it returns object

#
    [SerializeField] private float mana;
    [SerializeField] private float manaRegen;
    [SerializeField] private int gold;

    internal object GetGold()
    {
        return gold;
    }
    internal float GetMaxMana()
    {
        return maxMana;
    }
    public float GetCurrentMana()
    {
        return mana;
    }
unreal valley
#

So i have a dilema where I want to be able to call this only 1 time but be able to "refresh" i guess would be a lack of a better word, the PASSIVE Abilities Buffs if say the level got changed.

I've been trying to think of how to not put it in Update, cause that will just call the passive buff to be added over and over again. Not really sure how to implement this without someone basically looking at all my code?? I would assume.

TLDR: I want to "use" the passive ability ONCE but keep the Buff rolling infinitely.

Snippit of what I was calling in update to test VVVVVVV

GetAbilitiesFromCurrentJob().Find(x => x is PassiveAbility && !x.BuffsBuffsCanStack).Buffs.ForEach(x => x.ApplyBuff(Character as Player));

What im currently also trying in Start to test VVVVVVVVV

private void Start()
        {
            foreach (var ability in GetAbilitiesFromCurrentJob().Where(ability => ability is PassiveAbility && !ability.BuffsBuffsCanStack))
            {
                ((Player)Character).PlayerCombatSystem.UsePassiveAbility(ability as PassiveAbility);
            }
        }
visual basin
proper flume
visual basin
#

Well

#

Idk bro but a vector 3 seems to have 3 coordinates to me

#

A vector2 has 2 coordinates

fiery hill
#

A Vector3 with 2 coordinates sets Z to 0 as default...

rocky helm
#

Does InverseTransformPoint also take into consideration the transforms rotation?

late lion
#

Position, rotation and scale.

thin aurora
#

I think that was the point being made

proper flume
#

I dont want to

thin aurora
#

What does Roblox have to do with any of this

proper flume
#

In roblox you have to set all 3 numbers

#

But roblox is trash

thin aurora
#

Roblox is trash because they force you to set all three parameters?

#

There's a whole lot wrong with what you just said but you do whatever you want to do. Just post in #💻┃code-beginner next time and perhaps look up how to make a basic mesh on google

#

If you want my suggestion, look up how to make a basic quad, or billboard plane, and then do that four times

karmic rose
#

Hi there. Let's say I have an Abstract Class Ennemy that inherits from monobehvior. I have several different script that inherits from Ennemy. How can I store the reference of an Ennemy Script on an object.

GetComponent<Ennemy>() does not work (because Ennemy is an abstract class) so what is the solution ?

scarlet viper
#
        foreach (Transform folder in folders)

is this as fast as array?

leaden ice
fervent furnace
#

get abstarct class will work

scarlet viper
karmic rose
wintry crescent
leaden ice
scarlet viper
#

thank u

karmic rose
#
        Debug.Log(BT.name);```
fervent furnace
#

use tryget to check if some child class script exists

leaden ice
karmic rose
#

Sorry pressed enter too soon x) just a minute x)

leaden ice
karmic rose
#

So I have this class:

public abstract class BehaviorTree : MonoBehaviour

And some class inheriting from it including this class:

public class SpikeBoiBT : BehaviorTree

I attach SpikeBoiBT to the root parent of the ennemy object.

On one of the child object of the ennemy object, i have another script with :

    BehaviorTree BT;
    
    private void Start()
    {
        if(!transform.root.gameObject.CompareTag("Player")) BT = transform.root.gameObject.GetComponent<BehaviorTree>();
        Debug.Log(BT.name);
    }

The Debug.Log return a NRE.

Is there something I missed ?

#

Oh nvm I am a idiot --'

#

thanks for the help though 🙂

fervent furnace
#

the debug.log will always run

scarlet viper
#
public void Categorize(int index)

when u press a button u can make it pass integer or string or something to an OnClick public method
is there a way to make it include itself ?

muted cave
#

I don't know if this was the right channel to do this in, but I have this wierd issue with robot kyle where he is just not rendering any of his textures in. How do I fix this?
Image

leaden ice
# muted cave

looks like you're using a material that isn't supported by your render pipeline

#

e.g. you're using a BIRP material for URP or vice versa

#

(or perhaps no material at all)

muted cave
#

I use android based type build. Also: it does have a texture on it. It has robot kyle's.

leaden ice
#

android is also not relevant

trim schooner
leaden ice
#

oh that too lol

muted cave
#

I just want proper instructions how to fix this.

#

That's it.

leaden ice
#

what render pipeline are you using

#

what RP are those materials from

trim schooner
#

Use a shader on the material that is supported by your selected renderer pipeline. To get further help take it out of this channel.

muted cave
muted cave
pliant gorge
#

Hello, i'm having a 3d game where i need to know when the collider has hit my camera's view edge, how can i do that?

mild spear
#

Hello! How to raycast objects without collider?

leaden ice
leaden ice
#

what are you trying to accomplish

mild spear
#

I solved my problem. Thanks

fervent furnace
#

the moveVector has noe been normalized

main shuttle
#

Normalize the moveVector indeed.

leaden ice
#

moveVector = Vector3.ClampMagnitude(moveVector, 1); (between your last two lines)

#

is my preferred approach

#

normalizing loses all the values between 0 - 1 on a joystick

#

clamping will not

fervent furnace
#

yes but necessary

main shuttle
#

I agree with ClampMagnitude, its better for when you have analog input

leaden ice
#

doesn't matter

proper flume
#
mesh.vertices = new Vector3[]
{
    vec1,
    vec2,
    vec3,
    vec4,
};```
Can someone explain this? This Vector3 somehow accepts 4 vector 3's
leaden ice
#

Vector3[] means "array of vector3s"

proper flume
#

ohhh okay

leaden ice
#

arrays are basically a fixed-length list of things

proper flume
leaden ice
proper flume
leaden ice
#

that's python

#

this is C#

proper flume
#

Add To Array Using Array. Append() Method C#

#

??

leaden ice
proper flume
#

what

leaden ice
#

and if it did it would create a new array

proper flume
#

it was literally aut orecommended

leaden ice
#

by who

proper flume
#

vsc2022

#

wait just vs 2022

leaden ice
#

This is a Linq method

#

it's not part of the array type

proper flume
leaden ice
#

and it will not return an array, it will return a new IEnumerable

#

returns a new sequence that ends with element

#

not an array

proper flume
#

what

leaden ice
#

try it and see

proper flume
#

then is there something i can store variables in and add things to it

leaden ice
#

A List

proper flume
#

Ok i changed it thanks

#

vertices.Add(vec1);

vec1 is Vector3(0,0) by the way

#

help pls

main shuttle
leaden ice
proper flume
#

List<Vector3> vertices;

#

I did

leaden ice
#

this is a variable that can reference a list

proper flume
#

what how do i make it then

leaden ice
#

but it is not pointing at any actual list

#

List<Vector3> vertices = new List<Vector3>();

#

or the shorthand version:
List<Vector3> vertices = new();

proper flume
#

Thanks

#

What does collection is of a fixed size mean

west sparrow
#

Thats an array. It has a specific size by design, to change it would mean creating a new array.

#

Hence why it was said you can't append to the same array, as it is a fixed size.

lunar kestrel
whole gull
#

can someone help?

rigid island
whole gull
#

I want to have sprites that act as billboards but only in sceneview

rigid island
#

this is a editor only function

whole gull
#

i want to use it only in the editor

#

do i have to declare my script somehow that its editor only?

rigid island
#

this wont work in game export you know this yes?

whole gull
#

yes

fervent furnace
#

#if UNITY_EDITOR

lunar kestrel
whole gull
#

@rigid island I'm using this for invisible objects that have logic, for example an object that acts as a spawn position. Instead of using the unity label gizmo thing (which I find very ugly), I want to give these things Icons which I can see in the scene view, but ingame its not relevant

wintry crescent
#

But yes you need to wrap it in #if UNITY_EDITOR or your build will crap out

whole gull
#

thanks guys

rigid island
#

you can assign custom icons to gizmos too iirc

whole gull
#

LOL

#

you are right! 😄

#

omg

rigid island
whole gull
#

I will do that instead 😅

whole gull
#

I have a really stupid problem, I have a shotgun which fires multiple pellets. When the pellets hit an enemy, they call the "TakeDamage" function. Inside that function I checked if Health is below 0 and call the "Die" function. When the enemy has low hp, all pellets cause the if to be true and "Die" gets called multiple times, which is a problem... I can't think of a cool solution other than having a flag if "Die" was called already and just dont do anything if a "hasDied" flag is true... (does this even work?)

#

When all pellets call this function, do these run concurrently? Or does Unity have a call order internally?

somber nacelle
#

only one line of code will be running at a time. using a bool to flag whether it has died or not is sufficient

whole gull
#

in that case, how is this possible? I destroy the gameobject in the die funciton

#

i guess destroying happens on the next frame?

somber nacelle
#

correct, calling Destroy just queues it up to be destroyed. it won't actually be destroyed until the end of the frame

whole gull
#

why is a flag not sufficient?

#

I mean i dont like the solution anyway but i thought it would

#

oh

#

sorry

#

I misread your comment

#

alright, I guess I jsut do that for, maybe im stupid and thats the completely right solution anyway 🙂

fervent furnace
#

i have met some simliar problem finally i realize thare maybe multipe callback from physics engine

#

so you need a flag to lock it

#

in your case i think you can lock it by if(hp<=0)early return;

whole gull
#

true!

plucky knoll
#

The code is meant to set a create a network object and set it as a child of the clients, but it only works on hosts, it spawns the object in fine for all clients but when it comes to making it a child the clients get an error of “only the server can reparent network objects” I’ve tried everything go get this working with rpcs to get the host to do this on clients behalf but all it does it make that client parented on the hosts side too(what I wanted but I also need it parented for the client) I’m completely out of ideas to fix this please help

#

It’s literally killing me, 3 days trying to fix it now and nowhere I look online I can find an answer that works anything I try makes it more broken than this ^

leaden ice
plucky knoll
#

Sorry

merry sierra
#

hi so currently i have a car with wheel collider, whenever i try to change the cars location like reseting cars locations then it goes to the resetted location and comes back to the original location in a split second do anyone know why its happening

leaden ice
merry sierra
#

rigidbody is there

leaden ice
#

what if you make the RB kinematic, then teleport it, then make it not kinematic again

merry sierra
#

that thing is also not working

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

merry sierra
#
input.gameObject.GetComponent<Rigidbody>().isKinematic = true;
        yield return new WaitForSeconds(1);
        input.gameObject.transform.position = spawnPoints[input.playerIndex].position;
        input.gameObject.transform.rotation = spawnPoints[input.playerIndex].rotation;
        input.gameObject.GetComponent<Rigidbody>().isKinematic = false;
#

this is what i am doing in courotine

#

it works in editor but not in build

hidden gulch
#

i was searching how to simulate AI FOV and i found someone using these lines of code:

        var toPlayer = (player.transform.position-transform.position);
        var angle = Vector3.Angle(transform.forward.normalized, toPlayer);
        if(angle<FOV/2)
        {
            //raycast to see the player, but thats irrelevant to my question
        }
```could anyone explain to me why is the fov divided by 2 in this code?
burnt crypt
#

how do you deal with the fact that people can load your game in dnspy and edit the sources

#

if its online

leaden ice
burnt crypt
#

you get cheaters otherwise

#

if you ignore it

leaden ice
#

if you have an online competitive multiplayer game you use a combination of server-side validation of player actions and ever-more invasive client side anticheat software

burnt crypt
#

people can fly just under any serverside anticheat while still gaining an advantage

merry sierra
burnt crypt
#

ive seen a unity plugin for an anticheat. it was really bad, i could just disable it lol

leaden ice
#

that's the reality

burnt crypt
#

i want to see how you guys deal with it. i reversed a game recently where the guy paid for an anticheat plugin but the fact that c# compiles to bytecode ruins all security

merry sierra
#

and it worked

leaden ice
earnest gazelle
#

I have a problem with addressable assets when building the project. It is completely OK in the editor.
There is a collection list with 90 elements. They are SOs. It is OK in the editor as I mentioned but in runtime, it logs 360!!! and then I get an exception exist same key because they are populated into a dictionary

burnt crypt
#

let me see if i can find it

leaden ice
burnt crypt
#

i guess a lot of it falls to proper integration of the anticheat plugin

proper flume
#

does Collection is not fixed meaning it has to be a list?

burnt crypt
#

it would be good if you guys could write all core anticheat stuff in c++ and properly compile it

leaden ice
burnt crypt
#

cause in c# i can just modify event handlers for when a cheat is detected

merry sierra
# hidden gulch what

basically the center of the screen so that you can measure the side angle and do stuff according to it
like if your fov is 120, half is 60 and then you can do like if angle < 60 do something and andle > 60 do something this is what i think not sure

burnt crypt
#

clientside at least

proper flume
#

opening vs 2022 wait

#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class TestGenerator : MonoBehaviour
{

    Mesh mesh;
    List<Vector3> vertices = new List<Vector3>();
    List<Vector3> triangles = new List<Vector3>();

    public float chunkWidth;
    public float chunkHeight;
    public float Amplitude;
    public float Scale;
    private void Start()
    {
        CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(1, 1), new Vector3(1, 0), new int[] { 0, 1, 2, 0, 2, 3 });
        //CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(0, 0, 1), new Vector3(0, 1, 1),new int[] { 0, 1, 2, 0, 2, 3 });
    }

    void CreateShape(Vector3 vec1, Vector3 vec2, Vector3 vec3, Vector4 vec4, int[] triangles)
    {
        Mesh mesh = new Mesh();

        mesh.vertices = new Vector3[]
        {
            vec1,
            vec2,
            vec3,
            vec4,
        };
        mesh.triangles = triangles;
        GetComponent<MeshFilter>().mesh = mesh;

        vertices.Add(vec1);
        vertices.Add(vec2);
        vertices.Add(vec3);
        vertices.Add(vec4);

        triangles.AddRange(triangles);
    }
}
#

wait why is it addrange lol

merry sierra
# leaden ice if it worked wdym about finding a mistake

basically switching the position and undo the kinemetic directly after changing the position is making my car to go back to the original position but adding the small delay after undoing the kinematic part gives it some time to reset the position that i think what is happening right now

leaden ice
proper flume
#

i guess it was aut orecommended and i didnt notice it

leaden ice
#

as we told you before, arrays are fixed length

proper flume
#

no

leaden ice
#

they cannot be added to

somber nacelle
#

you have a local variable with the same name as your list field

proper flume
#

triangles is a list

leaden ice
#

no

#

it's not. You have another variable that is a list

proper flume
#

List<Vector3> triangles = new List<Vector3>();

leaden ice
#

with the same name

proper flume
#

oh yea

#

wait

leaden ice
#

int[] triangles) this takes precedence

#

in the method

proper flume
#

when i use vertices to make triangles

#

am i supposed to make the list a vector3 or int

leaden ice
#

triangles is an array of integers

#

they are indices into the vertex array

proper flume
#

can i add arrays to lists?

leaden ice
#

AddRange will let you add all the elements of any IEnumerable to a list

proper flume
#

no i changed it to add

leaden ice
#

if that's what you mean

proper flume
#

it was a accident

leaden ice
#

if it's a list you can use either

proper flume
#

no its a list

proper flume
#

its saying that its a int[][]

#

when its supposed to be int[]

somber nacelle
#

seems like triangles is now a List<int[]> considering you're adding an entire array to it

#

make sure it is a List<int> and use AddRange rather than Add to add all of the elements of the array to the list

somber nacelle
#

prove it

proper flume
#

oh it just did

#

yet my code

#

still doesnt work

somber nacelle
#

exactly. the reason it didn't work before was because you were calling AddRange on the local variable that just happened to have the same name as your field

proper flume
#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class TestGenerator : MonoBehaviour
{

    Mesh mesh;
    List<Vector3> vertices = new List<Vector3>();
    List<int> triangles = new List<int>();

    public float chunkWidth;
    public float chunkHeight;
    public float Amplitude;
    public float Scale;
    private void Start()
    {
        CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(1, 1), new Vector3(1, 0), new int[] { 0, 1, 2, 0, 2, 3 });
        CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(0, 0, 1), new Vector3(0, 1, 1),new int[] { 0, 1, 2, 0, 2, 3 });
    }

    void CreateShape(Vector3 vec1, Vector3 vec2, Vector3 vec3, Vector4 vec4, int[] trs)
    {
        Mesh mesh = new Mesh();

        mesh.vertices = new Vector3[]
        {
            vec1,
            vec2,
            vec3,
            vec4,
        };
        mesh.triangles = trs;
        GetComponent<MeshFilter>().mesh = mesh;

        vertices.Add(vec1);
        vertices.Add(vec2);
        vertices.Add(vec3);
        vertices.Add(vec4);

        triangles.AddRange(trs);
    }

    void UpdateMesh()
    {
        mesh.Clear();
        mesh.vertices = vertices.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.RecalculateNormals();
    }
}
#

so im trying to make it so i can make 2 of these triangles

#

and so it saves both of them

#

because right now one of them dissapears

#

like its overriding the whole mesh

#

oh wait

#

i forgot to call the function

#

lmao

mystic imp
#

Why is Health false?

somber nacelle
#

do you have a component called Health

proper flume
#

i got a error

somber nacelle
#

what is line 49

proper flume
#

mesh.Clear();

this is line 49

somber nacelle
#

then mesh is null

mystic imp
proper flume
#

what how

somber nacelle
proper flume
#

how is it null

somber nacelle
proper flume
somber nacelle
#

again, local variable with the same name as your field

#

please learn about variable scope

proper flume
#

public class TestGenerator : MonoBehaviour
{

Mesh mesh;
#

its not local

somber nacelle
#

it is because you redeclared it on the line you call new on

#

Mesh mesh = new Mesh(); has nothing to do with your field of the same name

somber nacelle
# mystic imp No

then what component are you expecting to get with the GetComponent call?

proper flume
#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class TestGenerator : MonoBehaviour
{

    Mesh mesh;
    List<Vector3> vertices = new List<Vector3>();
    List<int> triangles = new List<int>();

    public float chunkWidth;
    public float chunkHeight;
    public float Amplitude;
    public float Scale;
    private void Start()
    {
        CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(1, 1), new Vector3(1, 0), new int[] { 0, 1, 2, 0, 2, 3 });
        CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(0, 0, 1), new Vector3(0, 1, 1),new int[] { 0, 1, 2, 0, 2, 3 });
        UpdateMesh();
    }

    void CreateShape(Vector3 vec1, Vector3 vec2, Vector3 vec3, Vector4 vec4, int[] trs)
    {
        vertices.Add(vec1);
        vertices.Add(vec2);
        vertices.Add(vec3);
        vertices.Add(vec4);

        triangles.AddRange(trs);
    }

    private void Updating()
    {
        mesh.vertices = vertices.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.RecalculateNormals();
    }
    void UpdateMesh()
    {
        if (mesh != null)
        {
            mesh.Clear();
        }
        else
        {
            mesh = new Mesh();
        }
        Updating();
    }
}
#

Why does this not work

#

Its supposed to do the exact same thing as before

#

Make triangles then save it and make it 1 mesh

proper flume
gray mural
#

does it throw you the same error?

proper flume
#

theres no errors

#

the script simply not working

gray mural
#

I see, it calls UpdateMesh in Start

#

but what is not working?

proper flume
#

as you can see in create shape function

#

then the vertices and triangles are stored in a list

#

then the mesh is created in the update mesh function

#

but the mesh is not visible

#

i dont even know if it exists

#

but all I know is that all the settings are correct cause the earlier code worked

gray mural
#

what was the earlier code?

proper flume
#

but this didnt update the mesh

#

so it only allowed for 1 shape creation

#

i need multiple of it

somber nacelle
proper flume
#

what

#

mesh renderer

#

and filter