#archived-code-general

1 messages Ā· Page 279 of 1

versed spade
#

Definitely pain

leaden ice
versed spade
#

Nope as I said, its running up the the debug.log for highScore. Its definitely running

#
    public void restartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        highScore = PlayerPrefs.GetInt("highScore");
        Debug.Log(highScore);
        Debug.Log("Checking if statements");
        if (highScore > 0)
        {
            Debug.Log("High Score is below 0!");
            highScoreText.text = "No Scores Currently";
        }
        Debug.Log("Checking the next if!");
        if (highScore < 0)
        {
            Debug.Log("High Score is above 0!");
            highScoreText.text = "High Score: " + highScore.ToString();
        }
    }```
dusk apex
leaden ice
#

you wrote below 0 when it's actually above 0

dusk apex
#

So highscore is never less than 0

leaden ice
#

so the if statements are working properly

dusk apex
#

It can never occur

versed spade
#

hol up

leaden ice
#

Are you confused about what < and > mean?

#

highScore < 0 means high score is less than 0

#

and vice versa for highScore > 0, which means high score is greater than 0

versed spade
#

That was def it. Sorry about that. These <> always get be befuddled. Greater than or less than were taught to be in the most gank way possible

leaden ice
#

the big side of the symbol is on the side with the bigger number

#

and vice versa

versed spade
#

Now I just gotta solve why its reverses to No Scores Currently afterward

versed spade
vale bridge
#

For programming behaviors in Unity ECS, do you create an author, a data container, and a system each time?

#

I suppose it's just separating the data from logic when compared to gameObjects if that's a correct way to think about it

#

On the other hand I was wondering if this means that compile time is longer since you have more scripts in general in comparison(This is just conjecture though)

vale bridge
#

ah thanks

split plover
#

is it safe to load a memory dump (.dmp) file from an untrusted source (ie, random end user)?

cosmic rain
#

Besides, without the right symbol files, it's just a useless pile of binary data.

split plover
#

i mean I just wasn't sure if it was safe to load into an IDE, I've been surprised by some things recently like the unsafeness of stable diffusion .dat files (due to pickling) and similar things around certain binary serialization formats

cosmic rain
#

It depends on how the data is loaded. But I've never heard any mention of dump files being dangerous.

#

I guess, it could be if you use untrusted symbol files, as then the data could be interpreted in an unwanted way.

split plover
#

well, its our debug symbols(pdb), so i'm not as worried about that, I just haven't looked at a dump file from a user before

cosmic rain
#

Theoretically, any file from untrusted source can be dangerous. If they used some kind of vulnerability in your ide debugger, it's totally possible to plant a virus or run some other malicious code. Historically, there doesn't seem to be any reported cases of that happening, but you never know.

#

If that does happen to you, you can at least be proud as the first person that got hacked by a dump file.😬

knotty sun
fiery saddle
#

Is there a way for Custom Property Drawer to use internal class?
AnimCommand works only if its public

thin aurora
#

My guess considering it takes a Type it's hardcoded to check if the class is public, so I'm afraid it's not possible

fiery saddle
thin aurora
#

IDE error is weird on a Type

#

What is the error?

fiery saddle
#

But it doesnt make much sense since Unity shows internal class in editor

#

So if I dont have custom drawer it is shown in editor, but cant make custom drawer of internal class

thin aurora
#

That's not an error on the attribute but rather an accessibility error related to the project as a whole

#

AnimCommand appears to be in a different assembly, and making this internal restricts it to that assembly only

fiery saddle
thin aurora
#

If you want it internal but also use it here, either move it to the same assembly or add this to the .csproj file of the project that has the class:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>Add the assembly name of the class that should use the class</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>
thin aurora
fiery saddle
#

Yeah, iam not using assembly yet
my own assembly would fix it?

thin aurora
#

Well let me point out something else; if the class is in an assembly specific to the editor I am assuming that this assembly is not provided with builds as it's editor only

#

This would mean that you can no longer build because the code will not longer reference the class, causing an exception

#

So perhaps whatever you are trying to do should also be inside that editor assembly

#

You can test this issue by making it public again, verify the code compiles in the editor, and then building the project. It will fail with an error like "Unable to find AnimCommand class"

#

So the better thing to do here is finding an alternative which would allow you to do this, but abstracting the code that requires it into the editor assembly

fiery saddle
#

Iam creating asset store item, and would like make public only things that matter. Else should be internal, like this class

I just created my own assembly definition and it works

#

one assembly is for the whole project

thin aurora
#

You could move the assembly and related code to the editor assembly and have it call the actuall class from there

#

But perhaps you should share more code and context

fiery saddle
#

Would it be problem if I just put Drawer and runtime class into same project?

#

this works

thin aurora
#

The whole point is that you have an assembly that is not included in builds as it's specific to the editor

#

There are a million ways to go about this but a build assembly should not reference resources from an editor assembly

fiery saddle
sacred sinew
#

I have a save system to save my player health and it's shield but the health isn't changed when I load, but the shield does, here's my code : https://hastebin.com/share/lojebeyote.csharp

thin aurora
cosmic rain
knotty sun
#

also you should use Path.Combine(Application.persistentDataPath, "data.txt")

sacred sinew
thin aurora
cosmic rain
sacred sinew
thin aurora
#

So that means that health.shield is actually set, considering it's the value you apparently expect

#

So the issue is not related to this code

#

You can additionally check health.Health but "1" should parse into a float just fine

knotty sun
#

screenshot the console

sacred sinew
cosmic rain
#

So it's not just shield..?

knotty sun
# sacred sinew

absolutely nothing wrong there so something else must be affecting Health

thin aurora
#

So what exactly makes you wonder why "shield" is not being loaded when it clearly loads?

sacred sinew
#

thx everyone for helping me

stiff forge
#

Am I going crazy right now?

uint faceFlags = voxels[i].FaceFlags;
for (int j = 0; j < 6; j++) // <-- j is of type Int32, no?
  uint flag = faceFlags & 1 << 1; // <-- second 1 is of type Int32, right?

// Everything makes sense, so no errors

Whereas...

uint faceFlags = voxels[i].FaceFlags;
for (int j = 0; j < 6; j++) // <-- j is of type Int32, of course.
  uint flag = faceFlags & 1 << j; // <-- j is still of type Int32, yeah?

// Cannot implicitly convert type 'long' to 'uint'

Okay, I'll just cast it, then... But from where the hell does long appear?

thin aurora
#

Dunno, maybe a question for !cs

tawny elkBOT
cosmic rain
thin aurora
#

Also happens for me šŸ¤·ā€ā™‚ļø

knotty sun
#

most odd, 1 and j are both int

stiff forge
#

Right? Doesn't make sense to me

thin aurora
#

Only noticeable difference is that j is an int and 1 is perceived as Int32 but that doesn't explain anything

knotty sun
#

default type for numeric integers is int32

cosmic rain
quartz folio
#

I think C# can tell that 1 << 1 can be an unsigned int

#

and it allows the operation

stiff forge
#

That would explain why I need an explicit cast, but why from type long?

#

Is compiler just goofing?

knotty sun
#

not that it makes sense but the cast to Int64 would preserve the sign during the bit shift

#

-1 for example would require an upcast to Int64 to preserve all bits

stiff forge
#

It does seem like any bitwise operation between int and uint causes the error

knotty sun
#

yep, C# will not automatically allow you do to something which may lose data

#

1 << 1 is a compile time operation. 1 << j is runtime

pale gulch
#

how to create database Update .csv file, when a simple task done! and saved in .csv file

thin aurora
#

I don't think using excel files as a database is a good idea

orchid abyss
#

how to assign prefab child object to a different prefab object's script?

latent latch
#

they must both be part of another prefab together

#

if these objects are completely independent prefabs

pale gulch
#

please I want to collect some data from Player and put it in .csv after finishing the game

thin aurora
#

When it comes to games you would encrypt the data and write the bytes to a text files

#

But you can also just use regular text files and serialize the data as JSON into it, using Newtonsoft

#

JSON is generally the best format for sharing data but it won't be secure.

#

Then again, neither will .csv files.

pale gulch
#

I don't mind about secure to be honest its just fake data and it will keep change not stored

#

thank you sooo much FusedQyou

#

by the way I won't face a problem when build apk? @thin aurora

thin aurora
#

I have no idea how mobile works but Unity has a persistent data constant you can use as a place to save data

#

I would guess it works there too

#

As to what you actually save, I don't see why that would matter. I don't think there are restrictions

#

Note PlayerPrefs is also a feature you can use for saving so if you want simple saving you can also use that.

topaz plaza
#

Is there a way to turn an existing Prefab (that already is the parent to multiple Prefab Variants) into a variant of another Prefab? I just decided to make a more abstract prefab - but I find no way to make the existing root prefab a variant of that newly created Prefab

spring flame
#

transform.hasChanged is always true, right? It's not managed by Unity in any way. It's basically a flag that was put there for me tu manually set and unset, right?

gray thunder
#

Has the transform changed since the last time the flag was set to 'false'?

A change to the transform can be anything that can cause its matrix to be recalculated: any adjustment to its position, rotation or scale. Note that operations which can change the transform will not actually check if the old and new value are different before setting this flag. So setting, for instance, transform.position will always set hasChanged on the transform, regardless of there being any actual change.

late lion
spring flame
#

I wonder though, what's the best way to set it to false

#

because it can happen that multiple things could try to update certain things at different times

late lion
#

What problem are you trying to solve with this flag?

spring flame
#

Set it simply at the end of FixedUpdate, or something?

spring flame
late lion
spring flame
#

yes

neon plank
#

If I pass random numbers to Resources.InstanceIDToObjectList shouldn't it return null to them (they are invalid ids after all)? I noticed that it seems to crash.
Am I supposed to first call Resources.InstanceIdsToValidArray, and with the ones that returns true pass them to Resources.InstanceIDToObjectList?

spring flame
late lion
#

That way, you'll know if it has changed since you last updated the shader uniform.

#

If you set it in FixedUpdate, then you'll only know if it has changed since the last FixedUpdate.

unborn shard
#

Good morning, I'm finishing my first game. But I'm stuck on something that should be simple but I don't know how to do it. my boss summons these demons. However, if you die and try to press restart the game crashes, from what I think, it's because the demons are trying to follow the player, but the player is dead and has nothing to follow. How do I not have any more summons when the player dies? I will send the link to the codes below. demon controle; https://paste.ofcode.org/Wf8QGE6PrVX5AFQNX9ufNP player; https://paste.ofcode.org/RDJn7EBygswTGacKTiaxgQ boss; https://paste.ofcode.org/r5fYms2KqPpKb3KdNSqpfz

modest thicket
#

a very crude method would be to check if the player is null and if so, return out of the while loop.. a probably better way would be to have an event that you can register on, i.e. UnityAction OnDeath on the player, for example

unborn shard
#

I understood. thanks

long quarry
#

Hello, I am having a problem. When I put the enemies into the scene one by one, the player takes damage as I expected. However, if I put two enemies at the same time, the player doesn't take damage as I expected. It just takes damage from only one enemy's power

codes:
https://gdl.space/hajipocuka.cpp

long quarry
#

thanks a lot i will try to solve

leaden ice
#

They should both use the same script

#

Also the two you have are different

long quarry
#

i see, i will try that way thank you @leaden ice

eager tundra
#

I have the following situation:
Obj1 at scene root
Obj2 at scene root

I have Obj1 local position and Obj2 local position. I wanna make Obj2 move towards Obj1.
In this case, the local position is equivalent to the world position, since they're in the scene root.

But in case they weren't, I tried converting Obj1 local position to world position with TransformPoint and then later convert it to Obj2 local position by InverseTransformPoint. But this isn't working. Why is that?

leaden ice
eager tundra
leaden ice
#

your explanation was vague

#

but basically:
x.TransformPoint(somePosition) expects that somePosition is expressed as a local space position in the coordinate space of the object x

#

if it wasn't expressed that way, it won't have worked

#

for example some other object y has y.localPosition which is not expressed in local space of x unless y is a child of x

#

if y is a child of some other object then its local position is expressed as a coordinate in the space of that parent

#

local position is always in the coordinate system of an object's parent.

eager tundra
# leaden ice You'd have to show your code
    public void OnUpdate(ref SystemState state)
    {
        float deltaTime = SystemAPI.Time.DeltaTime;

        float3? playerPosition = null;
        foreach (var (transform, _) in SystemAPI.Query<RefRO<LocalTransform>, RefRO<PlayerTag>>())
            playerPosition = transform.ValueRO.TransformPoint(transform.ValueRO.Position);

        new EnemyMovementJob
        {
            DeltaTime = deltaTime,
            PlayerWorldPosition = playerPosition
        }.Schedule();
    }

    [BurstCompile]
    public partial struct EnemyMovementJob : IJobEntity
    {
        public float DeltaTime;
        public float3? PlayerWorldPosition;

        [BurstCompile]
        void Execute(
            ref LocalTransform transform,
            in EnemyMovement enemyMovement
        )
        {
            if (PlayerWorldPosition == null)
                return;

            float3 currentPosition = transform.Position;
            float3 targetPosition = transform.InverseTransformPoint(PlayerWorldPosition.Value);
            float3 newPosition = MathUtils.MoveTowards(
                currentPosition,
                targetPosition,
                enemyMovement.MoveSpeed * DeltaTime
            );
            if (math.distancesq(newPosition, targetPosition) < .1f)
                return;
            transform.Position = newPosition;
        }
    }

This is the code
I'm basically trying to make it hierarchy agnostic

#

If I simply skip the Transform/InverseTransform, it all works well because they're in the scene root

leaden ice
#

you're overcomoplicating it

eager tundra
#

The point is understanding it, I don't get why it isn't giving me the same results thinkies

latent latch
#

debug each operation and compare

little meadow
latent latch
#

if you're doing unnecessary operations and getting undesired results then I assume it's doing some extra matrix operations without caring what space it currently is in

leaden ice
#

I'm not sure your player world position makes sense

#
transform.ValueRO.TransformPoint(transform.ValueRO.Position)```
#

this in particular seems a little like nonsense to me

latent latch
#

oh yeah wat

leaden ice
#

I think you should just switch to LocalToWorld instead of LocalTransform all over this code

#

I'm inexperienced in DOTS/ECS

#

but whatever you need to just get world space positions

eager tundra
latent latch
#

can always grab the matrix4x4 from the transform and do the calculations yourself if you want to make actual sense oh, you just care for a point which you can probably just work out with differences

leaden ice
# eager tundra Yeah, that seems to be the issue

generally Position is your position in your parent's coordinate space but TransformPoint transforms a point in your own coordinate space to world space. So the input coordinate space here doesn't match the expected input coordinate space

#

because you're trying to reference non static fields from a field initializer

#

line1 etc... are all non static fields

latent latch
#

Even if you do serialize them, you still need to follow the rules of c#

leaden ice
#

everything on the right of the = sign is a field initializer

latent latch
#

if it's a mono, do it in start, otherwise use a constructor

leaden ice
#

Also you should rewrite the code to simplify:

public string[] lines;
public string str;

void Awake(){
  str = string.Join("\n", lines);
}```
#

Anytime you have "numbered" variables you are better off using an array or a list

plucky dagger
#

I'm having trouble spawning items in a specific room. When i do, the collision physics of the cube I'm using as my room act on the object and force them out

#

Wrong channel I think, though I was in beginner

latent latch
#

probably want to split layers for items and player for physics

unkempt zenith
#

How would I go about making sure an animation speeds up to match exactly a certain distance a GameObject has to travel?
A card can be played anywhere on the board. I want to play a little animation that nicely places the card, and I'm using MoveTowards to move the card to the board position. However, of course cards in the middle of the board are reached much quicker than those at the edge of the board. I guess what I'm trying to ask is how to go about animating objects without a fixed animation duration

latent latch
#

need to normalize the distance by a time

unkempt zenith
#

Yes, but I want the other way around :D Changing the animation speed so to speak

latent latch
unkempt zenith
#

Mm, let me record a gif of what I mean

latent latch
#

been a while since ive done some of this stuff but usually I remember it being pretty simple with adjusting the clips

#

there's some stuff there

unkempt zenith
#

So this example shows it quite well: The card moves from the hand to the board, but notice how the placement animation is much faster when placed on the lower row because the card does not have to travel that far

latent latch
#

right, you'd do a mixture of movetowards and change the animation speed playback

#

could also just play the animation when the card lands too

unkempt zenith
#

But wouldn't I need to know the time it takes to reach the destination to change the speed?

latent latch
#

well, you set a base duration of say 2 seconds

#

so it would be distance / duration animation duration / distance (one or the other lol)

#

which would be your animation playback speed per second*

#

or like I said, just play a normal animation when the card lands, and instead of adding an animation when moving you'd just move it with some parameters

unkempt zenith
#

Oh so calculate Vector2.Distance between the hand card and its target position and tinker with the divisor to find a nice playback speed? I think that could work!

#

Thanks for the help :)

latent latch
# unkempt zenith Oh so calculate Vector2.Distance between the hand card and its target position a...
public class ExampleScript : MonoBehaviour
{
    public Animation animation;

    public void PlayCardAnimation(float distance)
    {
        //normalizedSpeed = (animation.length / distance) / animation.length;

        //Ah, animation.speed is a multiplier so it may be this one instead. Try both.
        //Can also add a speed multiplier to distance
        normalizedSpeed = animation.length / distance;


        animation["PlayCard"].speed = normalizedSpeed;
        animation.Play("PlayCard");
    }
}```
#

probably look more into changing the speed because the api says it's done with states but I assume you can just change it for the clip alone? Not sure

#

maybe you have to edit the keyframes/curve if you did it by clip

swift falcon
#

If I have a class ConsumableItem that inherits from ItemInventory, can I use ConsumableItem in an ItemInventory variable?

leaden ice
#

I.E. if ConsumableItem : ItemInventory then ConsumableItem IS AN ItemInventory

swift falcon
lean sail
leaden ice
#

It's important to read your error messages and try to understand them

swift falcon
#

It was Cannot convert from ConsumableItem to ItemInventory

leaden ice
#

Then ConsumableItem did not inherit from ItemInventory as you said

#

again, show the code you tried.

#

including the definitions of those types and where you tried to use them

swift falcon
#

It's fine, I scrapped it because it didn't work. I was just asking for confirmation

leaden ice
#

it will work if you do it properly

#

You probably made a simple error. Conceptually what you asked for works fine.

lean sail
swift falcon
#

Hey guys I have an issue, it's the first time that I'm suing the new unity input system and I'm starting to find some issues.
One of the being that the character is really slippery so it's really hard to move since I'm creating a platformer.
Here is my code:

            {
                rb.velocity = new Vector2(1 * moveSpeed * speedMultiplier * 0.8f, rb.velocity.y * jumpForce/1.5f);
            }
            if (moveDir.x < -0.1f)
            {
                rb.velocity = new Vector2(-1 * moveSpeed * speedMultiplier * 0.8f, rb.velocity.y * jumpForce/1.5f);
            }
            if (moveDir.x == 0)
            {
                rb.velocity = new Vector2(0 * moveSpeed * speedMultiplier, rb.velocity.y);
            }```
Like this everything works fine, but the issue is the last if statement, where it's written "if moveDir.x == 0" because by doing this I can't apply any force to the game object other than just walking.
The issue is that if I remove that part the player becomes slippery and I don't know how to fix this
#

My idea was using something similar to "GetAxisRaw" that I remember used to do the same thing that I need but for the new input system

hard viper
#

this is going to sound really dumb… but let’s say I have a Stack, and want to potentially remove an entry… that might be in the middle of the stack.
Is there any way to do this without essentially doing ToList() and remaking the whole thing?

wicked scroll
little meadow
#

honestly, this is why stack and queue suck

hard viper
#

i have for 5 months now. Until right now

wicked scroll
#

Times Change

little meadow
#

they're great in theory but sooner or later you just want a list

hard viper
#

it’s for a draw history, so I can Undo/redo. And I want to check that the current entry isn’t effectively just doing nothing.

wicked scroll
#

but yeah, the point of these structures is the restrictions they enforce, so if those restrictions are getting in the way I say to just use a different one

hard viper
#

actually… maybe I don’t need to do that at all. the stack lives on!

wicked scroll
#

hah, and sometimes those restrictions help you to save time by forcing you to think things through! nice

hard viper
#

in my case, they really should be a stack

#

i’m trying to check if the commands in my stack (corresponding to one press of an Undo button) is equivalent do doing nothing

wicked scroll
#

it would probably be much easier to just only insert real operations? maybe you end up with the same problems though

#

pretty interesting question...you could sim the state forward or you could implement a way for each command to check if it will be a no-op, but both of those sound like a lot of work to me

hard viper
#

it’s just a bit messy because of how my level editor works

fervent furnace
#

undo/redo can be implemented by two stacks

stack a:1 2 3 4 5 6 7 8
stakc b:(empty)
```eg if you undo to 3, pop 8 7 6 5 4 from stack a and push to stack b
```cs
stack a:1 2 3
stack b:8 7 6 5 4
```with some checking (if some elements are null eg 4, 7)
```cs
stack a:1 2 3
stack b:8 6 5
```for redo, just pop stack b and push back to stack a
if one new operations is done eg 9, then clear stack b
```cs
stack a:1 2 3 9
stack b: (empty)
```but i will just keeping one list and two pointers and only push non null operation
hard viper
#

when you write X, it deletes what is there, logs the deletion, writes X, then logs the addition

hard viper
#

but a single undo/redo entry is also expressed as a stack of changes

wicked scroll
#

oh, maybe what you actually want is batching, do you have that?

#

guess so

fervent furnace
#

find out if the operation can cancel out each other is not good idea.....

hard viper
#

i mean like:
ā€œbackspace to delete A, then type Aā€
as one entry should be nothing. So even if you click and do that, you should not need to click undo one time to do nothing

wicked scroll
#

yeah, i think you would want to batch those together into one undo

hard viper
#

they are

#

but i’m trying to check the undo before I push it to the undo stack

wicked scroll
#

then every 'undo' press should do something, right?

hard viper
#

correct

wicked scroll
#

i guess i'm trying to imagine a situation where this matters

#

like what sort of thing is the user doing where they'd end up with an 'empty' undo in the stack? i agree that trying to collapse together actions which cancel each other out is a bit much

#

but maybe i'm misunderstanding

hard viper
#

imagine you are in paint, and drawing to the canvas. You now draw a red pixel onto a red pixel

#

the Undo stack should not be changed

wicked scroll
#

i see what you're saying but i don't think it matters at all

hard viper
#

or at least I do not want it to be changed

wicked scroll
#

like the lift to solve this is just not worth it for what you gain

hard viper
#

i don’t like it, it makes me unhappy, so I want it to be different

wicked scroll
fervent furnace
#

you can check if the operation is exactly the same as (all the states) stack top

wicked scroll
#

ah yeah that's true

#

you also could maybe do this at a higher level, e.g. do some validation before the actions are dispatched to ensure they aren't no-ops

fervent furnace
#

but i think this is not friendly to command pattern,
you have is operator btw

hard viper
#

my current solution:

/// <summary>Check if the most recent growing entry has just the given TilePlacementInstance
/// on the top. If it does, remove it and return true. Else return false.</summary>
public bool TryUnlogLastTile(TilePlacementInstance instance) {
    if (!loggingNewEvent && !loggingRedoEvent) return false;
    if (currentGrowingEntry.placements.TryPeek(out TilePlacementInstance recentTile)
        && recentTile == instance) {
        currentGrowingEntry.placements.Pop();
        return true;
    }
    return false;
}```
Invoke this right before writing a tile has been added to the canvas
wicked scroll
#

so that if i try to paint a red pixel red, nothing happens

hard viper
#

It would look like:
red pixel
delete red pixel, log old pixel was red
write red pixel
tryunlogRedPixel
If it was previously the same red pixel, done
If not, log the new red pixel

#

(also that's a struct btw)

#

Then it is easy when logging a new undo entry to abort if the stack count is 0

#

It won't catch times where the undo entry has a bunch of crap in it, but it only matters to block if the stack for the one undo press is only the one tile.

#

ty for helping me think through it

viscid swift
viscid swift
#

I thought this is vscode extension, not unity assets.

#

dev-logs looks good to me

leaden ice
#

except in those channels

viscid swift
#

I understood. Thank you. I'll move to dev-logs

steep herald
#

Do I have a way of knowing what vertices unity duplicated during the mesh import process other than a distance check?

quaint rock
#

talking like ones that were duplicated because of uv splits and normal splits

steep herald
#

normal splits

#

I assume actually, h/o

quaint rock
#

well verts in the same location with different normals

#

or just verts in the same location as eachother

#

whats the reason for needing to know? might be a other way to approach the problem

steep herald
#

In the process of writing a solver based on positions based dynamics. A part of the solving process is to project distance constraints.

I am trying to sample a mesh and generate the distance constraints based on the mesh's vertices, but I'm realizing now that it won't be that straightforward.

Current plan is to sample all verts for "duplication", generate a list of unique vertices. Bind all the duplicates to their unique counterpart and operate on the unique verts. Then I can just iterate on the bound indices for the skinning process.

#

It's kind of an ugly layer to strap on top

round violet
#

is this the same as maxUse -= 1 ?

#

i just found this randomly

#

i wish i found this sooner

mossy gust
#

so guys
im making a rhythm game
but im stuck on how to make a system where the notes go down and you can hit them

naive swallow
round violet
#

ty

chilly surge
round violet
#

yep im on the page rn

#

very useful

somber nacelle
#

crazy how useful knowing the absolute basics of the language is. who would have thought

round violet
#

sorry man i started csharp and unity only 4 months ago

#

i dont see how hitting on me for this small thing is helping

grave tundra
#

has anyone implemented marching cubes and can give me a hand>

unkempt zenith
unkempt zenith
fiery saddle
unkempt zenith
#

Mmm I see. I've not really used them, yet, but it might be worth a shot!

clear halo
#

Hello. How to I properly declade a NetworkList<int>? I want it to be initiated with numbers from 1 to 12.

dull quarry
#

Hi, I don't want you to see my character while others see it. I did it a bit by myself and a bit from a guide and I got an errors: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gamemeneger : MonoBehaviour
{

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    
    if (gracz == gracz.mojgracz)
    {
        gracz.gameObject.transform.Find("Man_Full").gameObject.SetActive(false);
    }
    else
    {
        gracz.gameObject.transform.Find("Man_Full").GetComponent<Renderer>();
    }
    if (gracz.team == Team.BLUE)
    {
        gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.blue;

    }
    else
    {
        gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.red;
    }

}
public void SpawnGracza()
{
    GameObject mojgracz = PhotonNetwork.Instantiate("Gracz", new Vector3(58.29f, 0f, -837.0149f), Quaternion.identity, 0);
    mojgracz.GetComponent<FirstPersonMovement>().enabled = true;
    mojgracz.GetComponent<Jump>().enabled = true;
    mojgracz.GetComponent<Crouch>().enabled = true;
    mojgracz.transform.Find("First Person Camera").gameObject.SetActive(true);



}

}

#

and secound script: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gracz : MonoBehaviour
{
public static gracz mojgracz;
public string nick = "";
public PhotonPlayer pp;

public Team team;

public static List<gracz> gracze = new List<gracz>();

public static void debugujliste()
{
    string dbgS = "debugujliste" + gracze.Count;
    int i = 0;
    foreach (var gracz in gracze)
    {
        dbgS += "id:" + i+ "nick:" + gracz.nick + "team:" + gracz.team;
        i++;
    }
    Debug.Log(dbgS);
}

private void Update()
{
    
    if(Input.GetKeyDown(KeyCode.L))
    {
        debugujliste();
    }
}
public static gracz ZnajdzGracza(PhotonPlayer pp)
{
    for(int i =0; i < gracze.Count; i++)
    {
        if (gracze[i].pp == pp)
            return gracze[i];
    }
    return null;

}

}

public enum Team { RED, BLUE}```

#

If someone helps me, I will love him
ā¤ļø

scarlet kindle
#

Hey I'm having a strange issue where the OnSceneLoaded event is calling 4 times each time 1 scene is loaded?

heady iris
#

Did you disable domain reload?

#

If so, you need to make sure you're unsubscribing from static events

#

also, you might just be subscribing repeatedly

scarlet kindle
#

hmm, well, the subscription would be this line right?

SceneManager.sceneLoaded += OnSceneLoaded;

that's in the Start() function of a Singleton, so I don't think that case.

as for the disable domain reload, I don't think I did... but i'll look into that thanks

#

is that the problem that I don't have it enabled?

somber nacelle
#

no

#

just make sure you are unsubscribing from the event in OnDestroy or something

scarlet kindle
#

ah. yes, the singleton does get recreated if I reset my game (it's a roguelike)

#

so that would make sense

#

i'll make sure to do that, thx

#

yep that fixed it! woohoo

dense estuary
#

Can somebody please refresh me rq on how to use the "new" input system? The way I did it before was using the InputActionAsset I made to assign InputAction components, but currently I am at a blank on how to do button detection. Something like this? ```cs
private void OnEnable()
{
jump = controls.Player.Jump;
jump.Enable();
}

private void OnDisable()
{
jump.Disable();
}
public void Jump(InputAction.CallbackContext Context)
{
if (Context.performed || IsGrounded())
{
return;
}
}```

leaden ice
#

As it is right now your Jump() function is not being used by anything

quaint rock
#

for a jump i normally just sub to its onPerformed

dense estuary
quaint rock
#

jump.performed += Jump;

#

where Jump is a method accepting the arg InputAction.CallbackContext

#

sub and unsub from it in OnEnable and OnDisable

#

then when ever jump is pressed your Jump method gets called

dense estuary
#

so like this? ```cs
private void OnEnable()
{
jump = controls.Player.Jump;
jump.performed += Jump;
}

private void OnDisable()
{
jump.performed -= Jump;
}```

quaint rock
#

yup, though you will still want to call Enable

#

like your previous one

#

though if you are binding to multiple controls, you could enable the whole action group instead of just the one action

dense estuary
#

Do I enable before checking performed, and disable after unsubbing?

quaint rock
#

it does not matter

#

as long as its enabled and subbed to

dense estuary
#

Alright cool, thanks :D

quaint rock
#

this is how i handle things that are just button pressed i want to call a function on

#

for other things i just poll for it in update

hard viper
#

and the method needs to be a function of InputAction.CallbackContext

dense estuary
# hard viper and the method needs to be a function of InputAction.CallbackContext

Like this? ```cs
private void OnEnable()
{
move = controls.Player.Move;
move.Enable();
jump = controls.Player.Jump;
jump.Enable();
jump.performed += Jump;
}

private void OnDisable()
{
move.Disable();
jump.Disable();
jump.performed -= Jump;
}
public void Jump(InputAction.CallbackContext Context)
{
if (Context.performed || IsGrounded())
{

}

}```

somber nacelle
#

fun fact, if you just subscribe and unsubscribe in Awake/Start and OnDestroy you only have to enable and disable the actions in OnEnable/OnDisable

hard viper
#

discord formating is being dumb rn

#
    private void OnEnable() {
        playerInput.Gameplay.MousePosition.performed += OnMouseMove;
        playerInput.Gameplay.MouseLeftClick.started += OnLeftClick;
        playerInput.Gameplay.MouseLeftClick.performed += OnLeftClick;
        playerInput.Gameplay.MouseLeftClick.canceled += OnLeftClick;
        playerInput.Gameplay.MouseRightClick.performed += DirectRotateButton;
        playerInput.Gameplay.Reject.performed += OnPressReject;
        drawTypeButton.OnBuildModeChange += ForceReleaseDraw;
    }

    private void OnDisable() {
        playerInput.Gameplay.MousePosition.performed -= OnMouseMove;
        playerInput.Gameplay.MouseLeftClick.started -= OnLeftClick;
        playerInput.Gameplay.MouseLeftClick.performed -= OnLeftClick;```
#

This is what mine looks like

icy depot
#

this is a silly question but... tilemaprenderers can be referenced, right? I need them to be

somber nacelle
tawny elkBOT
icy depot
#

Oh Tilemaps

#

whoops

#

thank you, I'll configure it asap

fluid lily
#

will the |= operator call the right hand if the left hand is already true?

#

Like is it equal to
bool myBool = SomeValue();

myBool = myBool || SomethingElse();

#

where if myBool is true it doesn't call SomethingElse()

somber nacelle
chilly surge
somber nacelle
#

that's not a thing

chilly surge
#

Huh.

somber nacelle
#

there is no ||= operator

chilly surge
#

Not sure why it's not a thing.

fluid lily
#

I agree it should be a thing, but I am just doing the second way I said now.

unkempt zenith
#

Oh god please no. I want to be able to have readable code bases

chilly surge
dense estuary
chilly surge
#

I feel like being able to short circuit is a good enough reason to have ||= and &&= added to the language.

lean sail
#

I thought all the operators could be written like that too

unkempt zenith
chilly surge
unkempt zenith
#

Yes. I'm struggling to find an actual use case though

chilly surge
#

I mean, lots of languages have it, and the original question asks for it (presumably wanting short circuit)

dense estuary
#

if (this = 19 ||= 20) {)

#

but then again it is kinda not necessary

unkempt zenith
#

Oh god

#

Please no

#

I think it's better to write your code in a way that makes it easy to read, rather than quick to write

chilly surge
#

By that logic we shouldn't have any compound assignment at all.

unkempt zenith
#

No, compound assignments for integers are not used in expressions

#

||= and &&= would be used in expressions

#

Hell no

chilly surge
#

||= and &&= is no less useful than +=, -=, or ??=.

dense estuary
#

It is just quick to right

#

it isnt very useful and its harder to read

chilly surge
#

That's a very questionable take, ??= is very much used everywhere in C#, compound assignment is not limited to arithmetic operators.

#

Many other languages also have ||= and &&=, not sure what more evidence you need that they have their utilities.

unkempt zenith
#

I'm not saying other languages don't have them. I'm saying hell no to C# having them.
The thing is that they are used on bools, which themselves are expressions.

short badge
unkempt zenith
#

But who am I to gate keep šŸ¤·ā€ā™‚ļø
If you like it you like it ^^

unkempt zenith
short badge
#

ah

#

sorry was late to the convo lol

chilly surge
#

Doesn't seem like GitHub code search allows back reference regex groups, so I can't do a search on foo = foo || ... pattern.

#

But just searching /[a-zA-z0-9]+ = [a-zA-z0-9]+ \|\|/ (which matches foo = bar || ...) and even the first page of dotnet/runtime repo is full of examples that could be simplified with ||=.

grim fiber
#

hey quick question how to do you random.Range a set value again

#

wait never mind i got it ahha

short badge
#

to the person asking for random value and deleted the message:
You could set float min and max for the numbers, then you could Random random = new Random(); and then you could generate the number with randomValue = random.Next(minValue, maxValue);

minValue and maxValue are the float numbers*

grim fiber
#

yea thx dude i was just like having a brain fart haha

quaint rock
#

can also just use unitys random instead

short badge
#

np

quaint rock
#

Random.Range(min, max)

short badge
#

or that, but this came quicker to mind lol

grim fiber
#

i was just a bit confused why i couldnt set the value in the begining

dense estuary
#

Is this a good way of detecting sprinting input? Sprint being a bind of an analog value action: isSprinting = controls.Player.Sprint.ReadValue<float>() > 0;

quaint rock
somber nacelle
somber nacelle
#

well, I personally just make my sprint action a Button and subscribe to the performed and canceled events. then you don't need to poll the value constantly

dense estuary
#

That works much better, thank you!!

bitter saffron
#

Hey there => I'm using netcode for game object. I add children to a prefab with a network object at runtime, then spawn that prefab but the Children are not spawned on clients. Is it something I'm not supposed to be able to do because the template gameObject original prefab doesn't have these children in it ?

shell scarab
#

how do I use IJsonMigration? The example that is given doesn't make a whole lot of sense to me. Should I be implementing this on a class that is saved? I can't imagine it's magically called when versions don't align. Or am I suppose to call its method if it fails to serialize?

dry mural
#

I'm using BlueUnity plugin to read data from Arduino Uno HC-05. This BlueUnity plugin basically calls a Java class and will return a string containing JSON formmated text. This is the example provided by BlueUnity plugin to read data.

public class BluetoothService
{

    private static AndroidJavaClass unityPlayer;
    private static AndroidJavaObject activity;
    private static AndroidJavaObject context;
    private static AndroidJavaClass unity3dbluetoothplugin;
    private static AndroidJavaObject BluetoothConnector;

    // creating an instance of the bluetooth class from the plugin 
    public static void CreateBluetoothObject()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            context = activity.Call<AndroidJavaObject>("getApplicationContext");
            unity3dbluetoothplugin = new AndroidJavaClass("com.example.unity3dbluetoothplugin.BluetoothConnector");
            BluetoothConnector = unity3dbluetoothplugin.CallStatic<AndroidJavaObject>("getInstance");

        }
    }
    public static string ReadFromBluetooth()
    {
        if (Application.platform == RuntimePlatform.Android)
        {

            return BluetoothConnector.Call<string>("ReadData");

        }

        return "";
    }
}

the problem is that when I try to call BluetoothService.ReadFromBluetooth from another script's Update function, the game stutters when the string is empty.
It freezes for 80ms (ReadFromBluetooth takes 80% of the duration) when the string is empty (not null). How to avoid this?

#

For additional context: It's stuck for around 50ms on the line "return BluetoothConnector.Call<string>();" in the profiling.

leaden ice
#

likely you'd want to process the bluetooth stuff on a background thread

dry mural
leaden ice
#

sure

#

and the java code is doing IO

dry mural
#

yes, I tried that as well

    private static Queue<string> messageQueue = new Queue<string>();
    public static void ReadDataInBackground()
    {
        while (true)
        {
            
            string data = BluetoothConnector.Call<string>("ReadData");
            // if (data.Length > 1)
            // {
            lock (messageQueue)
            {
                messageQueue.Enqueue((data == null).ToString());
            }

            // Adjust delay based on your needs (e.g., 0.1f for 100ms)
            Thread.Sleep(1);
        }
    }

    public static string GetNextMessage()
    {
        lock (messageQueue)
        {
            if (messageQueue.Count > 0)
            {
                return messageQueue.Dequeue();
            }
            else
            {
                return "";
            }
        }
    }

and when I try to run GetNextMessage in another script's Update, it returns as True meaning that the "string data" is null

dry mural
dry mural
leaden ice
dry mural
#

that was debugging whether the data is null or not

leaden ice
#

oh - you can just use ConcurrentQueue btw instead of manually locking

dry mural
#

hold a minute while i'm trying that concurrentqueue

leaden ice
#

anyway it's not going to change anything really

#

sounds like your Java function is returning null

#

and by the way

#

Thread.Sleep(1)

#

that waits for a single millisecond

#

you probably want to wait a lot longer than that, around 100ms based on what you said

#

And it's unclear exactly what this ReadData function does

dry mural
#

it gives the string back

leaden ice
#

It's unclear when and where you're calling that one

#

Oh you said Update

dry mural
# leaden ice Oh you said Update
void Update()
    {
        if (IsConnected)
        {
            try
            {
                string datain = BluetoothService.ReadFromBluetooth();
                if (datain.Length > 1)
                {
                    dataRecived = datain;
                    print(dataRecived);
                }

            }
            catch
            {
                BluetoothService.Toast("Error in connection");
            }
        }

    }
#

yes

#

basically this

#

when using queue I tried this

void Update()
    {
        if (IsConnected)
        {
            try
            {
                string datain = BluetoothService.GetNextMessage();
                if (datain.Length > 1)
                {
                    dataRecived = datain;
                    print(dataRecived);
                }

            }
            catch
            {
                BluetoothService.Toast("Error in connection");
            }
        }

    }
dry mural
#

ok so when I open the java class, the function is like this

    public String ReadData(){

        try {
            if(inputStream.available() > 0){

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                return reader.readLine();
            }
            else return "";
        } catch (IOException e) {
            return "";
        }
    }
#

this is the java code

#

based on your suggestion, I tried doing this

private static ConcurrentQueue<string> messageQueue = new ConcurrentQueue<string>();    
public static void ReadDataInBackground()
    {
        while (true)
        {

            string data = BluetoothConnector.Call<string>("ReadData");
            // if (data.Length > 1)
            // {
            // lock (messageQueue)
            // {
            messageQueue.Enqueue((data == null).ToString());
            // }

            // Adjust delay based on your needs (e.g., 0.1f for 100ms)
            Thread.Sleep(75);
        }
    }
chilly surge
#

How are you calling the ReadDataInBackground?

leaden ice
#

ok so honestly given the way the java is written

#

I would delete the Thread.sleep entirely

#

er wait maybe not

#

honestly wonder if it would be better to delete that if statement in the Java code and just have it block indefinitely

#

then you wouldn't need the sleep

dry mural
#
public class BluetoothConnection : MonoBehaviour
{
    public void StartBluetooth()
    {
        if (SimulateData) { isConnected = true; return; }
        if (!isConnected)
        {
            // isConnected = BluetoothService.StartBluetoothConnection(deviceName.text.ToString());
            isConnected = BluetoothService.StartBluetoothConnection("HC-05");
            // BluetoothService.Toast($"{isConnected}{!SimulateData}");
            // BluetoothService.Toast("HC-05" + " status: " + isConnected);
            // StartCoroutine(CReadBluetooth());
            thread = new Thread(() => BluetoothService.ReadDataInBackground());
            thread.Start();
        }
    }
}

the StartBluetooth will be called on button's OnClick

#

oh sorry in the java?

#
    public String ReadData(){


                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                return reader.readLine();

    }
leaden ice
#

Yeah I was saying like

        try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
          return reader.readLine();
        } catch (IOException e) {
            return "";
        }```
#

because that should just block until there is a line of data

#

as long as it needs to wait

#

otherwise the way you had it, it's going to return an empty string immediately when there's no data in the stream

dry mural
leaden ice
#

actually I don't see any circumstance in which this code should return null

#

SO that's weird for sure

dry mural
leaden ice
#

maybe some weirdness with how Unity handles plugins and multithreading

dry mural
#

when the string is empty but not null, it runs smoothly, I saw it in the profiler that it only stutters when it has characters in the string

#

i personally don't care if the java takes a shitton of time to read data, what matters is that the game freezes when waiting for incoming data

chilly surge
#

Have you profiled again to see what's causing the stutter with the changes Praetor gave you?

#

Now that the data reading in on a different thread it shouldn't block main thread anymore.

dry mural
#

which is not what I want

chilly surge
#

Ah.

leaden ice
dry mural
#
    public static void ReadDataInBackground()
    {
        while (true)
        {

            string data = BluetoothConnector.Call<string>("ReadData");

            if (data != null)
            {
                messageQueue.Enqueue((data).ToString());
                Thread.Sleep(75);
                
            }

        }
    }

I even tried this just for the piss but it gives me nothing instead, (well, the conclusion is that the data is always null)

signal moon
#

hi, may anybody tell me why in my chess game this script summons a queen after promotion correctly (1) but when i tried to change it with giving few options to the players it suddenly stopped working (2) The piece is always black and it spawns always on 1 side of the map, not where the pawn was?

#

only with queen promotion

#

with all 4 promotions

#

here i put the codes
without debug.log

{
    TakePiece(piece);
    Queen.SetActive(true);
    Bishop.SetActive(true);
    Knight.SetActive(true);
    Rook.SetActive(true);
    Debug.Log(piece.occupiedSquare);
    Debug.Log(piece.team);
    if (QueenPromote)
    {
        chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Queen));
        QueenPromote = false;
        Bishop.SetActive(false);
        Queen.SetActive(false);
        Rook.SetActive(false);
        Knight.SetActive(false);
    }
    else if (RookPromote)
    {
        chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Rook));
        RookPromote = false;
        Bishop.SetActive(false);
        Queen.SetActive(false);
        Rook.SetActive(false);
        Knight.SetActive(false);
    }
    else if (BishopPromote)
    {
        chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Bishop));
        BishopPromote = false;
        Bishop.SetActive(false);
        Queen.SetActive(false);
        Rook.SetActive(false);
        Knight.SetActive(false);
    }
    else if (KnightPromote)
    {
        chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Knight));
        KnightPromote = false;
        Bishop.SetActive(false);
        Queen.SetActive(false);
        Rook.SetActive(false);
        Knight.SetActive(false);
    }
    Debug.Log(piece.occupiedSquare);
    Debug.Log(piece.team);
}```
 i have this function currently
Queen, bishop, knight and rook at start are buttons 
this code doesnt work, it doesnt read the position
#

as we can see it loses the values mid code

#

any idea what had happened?

modern creek
#

quick question - is Piece a monobehaviour?

#

if so - don't do this:

        if (piece)

(we don't do that here meme)

It doesn't work like you might expect it to, since operator== is overloaded and means something different in unity (it means if it's null or has been destroyed this frame - which might be fine for your use case but .. you probably ought to not do that anyway since it's a weird construct)

#

    private void TakePiece(Piece piece)
    {
        if (piece)
        {
            grid[piece.occupiedSquare.x, piece.occupiedSquare.y] = null;
            chessController.OnPieceRemoved(piece);
            Destroy(piece.gameObject);
        }
    }


    public void PromotePiece(Piece piece)
    {
        TakePiece(piece);
        chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Queen));
    }

Also....... you're calling TakePiece in promote piece (first), then trying to access piece.occupiedSquare - it'll work because Destroy(piece.gameObject) doesn't actually kill it until the end of frame, but .. you should protect yourself against bugs like this by getting the square the piece is on first then destroying it and creating a new one

#

@signal moon Your PromotePiece and Promote__ methods are a mess - don't do this sort of wonky "loose" coupling where one hand sets a flag and expects the other hand to read the flag. Instead - just call promotepiece directly from promote__:

internal enum PromotionType { Queen, Rook, Bishop, Knight, }

public void PromoteQueen(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Queen);
public void PromoteRook(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Rook); 
// .. etc

private void PromotePiece(Piece selectedPiece, PromotionType promotionType)
{
  // remember to grab the square, team first
  Vector2Int coords = selectedPiece.occupiedSquare;
  TeamType team = selectedPiece.team;
  TakePiece(selectedPiece);
  chessController.CreatePiece(coords, team, promotionType);
}
signal moon
modern creek
#

i mean.. look at your piece class and see if it inherits from monobehaviour

#

is it

public class Piece {}

// or 

public class Piece : MonoBehaviour {}
#

if it's the first, you're fine, but even then I wouldn't do if (piece) .. that's kind of an old school (and unclear) way of doing checks.. it's valid but kind of clunky

signal moon
#

monobehavior

modern creek
#

then yeah, "double-don't" do if (piece)

#

that's not your exact problem but if you don't your way around c# and unity and why not to do it - just take my word for it, it'll be something that gets you when you least expect it. šŸ™‚

#

it's kinda like a safety on a gun.. you don't need it until you need it but when you need it, you'll wish you knew about it

signal moon
#

sure, thanks

signal moon
modern creek
#

no but that's "easy" enough to solve by keeping track internally which piece is promoting

#

you have some other problems here in your code - like you have "only one" queen/rook/bishop/knight game object but obviously you can have more than one

#

or maybe those game objects are the popup "select which piece to promote" objects? if so, disregard

#

oh, yeah, they are, i see - "rook choose"

signal moon
#

so i tried adjusting it, i got couple errors from that, but again, im not really yet good at managing other people code when they use different techniques ```internal enum PromotionType { Queen, Rook, Bishop, Knight, }

public void PromoteQueen(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Queen);
public void PromoteRook(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Rook);
public void PromoteBishop(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Bishop);
public void PromoteKnight(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Knight);

private void PromotePiece(Piece selectedPiece, PromotionType promotionType)
{
TakePiece(piece);
Queen.SetActive(true);
Bishop.SetActive(true);
Knight.SetActive(true);
Rook.SetActive(true);
// remember to grab the square, team first
Vector2Int coords = selectedPiece.occupiedSquare;
TeamType team = selectedPiece.team;
TakePiece(selectedPiece);
chessController.CreatePiece(coords, team, promotionType);
}```

modern creek
#

nevermind šŸ™‚ but to make your code a little less verbose, I'd parent them all under one game object and just show/hide that.. ie, something like "Select Piece Dialog" and then just turn that entire game object on/off instead of turning each of those objects on and off

#

yeah, it's not going to work directly - i didn't realize you had tied those game objects to PromoteQueen() etc

#

I don't quite see how you're tracking the piece that's promoting, but if you have a reference to it somewhere then just remove that parameter

signal moon
#

well, it should look like this in game: Pawn reaches promotion, it is killed, 4 buttons appear, when player clicks one of them the piece is placed here

modern creek
#
internal enum PromotionType { Queen, Rook, Bishop, Knight, }

public void PromoteQueen() => PromotePiece(PromotionType.Queen);
public void PromoteRook() => PromotePiece(PromotionType.Rook);
public void PromoteBishop() => PromotePiece(PromotionType.Bishop);
public void PromoteKnight() => PromotePiece(PromotionType.Knight);

#

right so... when the promotion dialog comes up, keep track of what the promotion square is, and based on what the user clicks, place a piece of that type on that square.. map the game objects button on click to PromoteQueen() for the queen button, rook for rook, knight for knight, etc

signal moon
#

god i already see sleepless (k)nights when i will try to make 90 cards affecting movement and board shrinking etc

modern creek
#

then your PromotePiece() method will take the type it's promoting to as a parameter

#

heh, well, you'll get there.. your code is a little wobbly and "hard coded" for different situations for now but .. just keep coding, just keep asking questions and you'll learn some of this stuff

#

then you'll have to work on the stockfish part of the code šŸ˜‰

signal moon
#

it currently looks like that in unity when i do it with my old not working code

#

ill ofc add something to prevent playing until chosen

#

when one button is picked, rest disappers

#

and the piece is spawned

#

right type of piece, just position and color are wrong

signal moon
#

and now im trying to understand how it works

#

i have created a 2d small game before so atleast i know what to do where in unity alone lol, but from coding im still weak

modern creek
#

heh.. well.. there's a lot to programming to be fair, and school/learning ain't easy, but .. just go slow when you bulk copy something else because if you don't understand how every single line works, then changing things will be an exercise in frustration

signal moon
modern creek
#

something else i would do that I noticed in your example that are going to be bugs waiting to happen - put brackets around your if/else clauses.. it's "legal" do omit them but the compiler isn't going to help you out when you do something like this:

if (something)
  DoOneThing();
else
  DoSomethingElse();

//.. then you decide to ...

if (something)
  DoOneThing();
  AlsoDoThisOtherThing(); // this is a bug!
signal moon
#

it is a shortcut for my part of tarot chess cards that i won't get any help in terms of tutorials

modern creek
#

you're allowed to use whatever information you want on the internet (including chatgpt).. but just be aware that if you're just "trying to make it work" by copying the bulk of it from somewhere else and then fiddling with random lines of code.. well.. you're gonna hate programming real quick that way.. instead, try to really understand what every single line does and if something isn't working like you expect.. breaking the problem down more and more until you find out what assumption you made is wrong. šŸ™‚

#

(but also, chatgpt is generally garbage for helping since it just spits out wrong answers with confidence)

signal moon
#

i would do it, i just don't have time for this, as school takes like 10h a day

#

the other 8 is sleep

modern creek
#

yeah, but also, there's no real shortcut for learning :p

signal moon
#

i know, but it is the only way i can achieve something in good time

modern creek
#

lemme maybe restate the ... strategy? Spend like 50% or more of your time strictly learning - just reading, absorbing, trying things out, testing things.. and if you spend that time well, the other 50% where you're actually not trying to learn but just trying to produce something will go way more smoothly. If you start with trying to do something first without knowing how to do it, it's just gonna be.. nightmares and take twice as long

#

programming as a career is basically carving out time specifically for learning some piece of tech.. it never ends, honestly, even if you are an expert in some area

#

i've been programming for more than 3 decades and i still google inane shit like "how to initialize an array of characters" or whatever

signal moon
#

well, i got badly injured and had to skip school for few months, and i programmed this thing: https://goshire.itch.io/undying-faith So its not like i have no idea what am i doing, i would learn commands but i find that im bored after 15 minutes, thats why im barely passing from grade to grade.

itch.io

Quick Hack&Slash Game, It's your time to shine!

#

And that quickly demotivates me to do anything, as im constantly tired, and doing boring things while tired is ..... it isn't

modern creek
#

two suggestions: coffee and ADHD diagnosis and meds šŸ™‚

#

or honestly, real hard self assessment if you want to program as a life choice.. programming is fun for some and torture for others.. once you have enough skill and tools under control though, the dopamine hits are there.. it's like small problem solving over and over and over and it feels great when things work and you know how to accomplish things

signal moon
#

well, im almost sure i have adhd, also im in one of the most requiring schools in the city, so maeby coffee really is a way, i just don't want to get addicted so early lol

modern creek
#

coffee addiction is underrated

signal moon
#

unless im doing something and solving by reading

#

like programming

#

that is why i hate school, you never do, you always read

modern creek
#

yeah well.. that's a part of it .. just mashing into doing things in programming doesn't always work all that well. I dunno, there's lots of people who make careers out of programming and don't often read the docs but.. if you can learn to enjoy that part of the process then it'll be a much more rewarding engagement

#

you have a whole life of "doing" in front of you.. enjoy the "just read" part of it while you still can :p

#

anyway i'm gonna homer-into-the-bushes here.. I think we hijacked the channel a bit to have this life convo. šŸ™‚

#

glgl on your chess project

signal moon
#

yea, i gtg, school bus is going in 15, ill just show what i have done so far, its not like im not doing 3x more than any other of my classmates in terms of game dev

#

ill dm you later about this if you can

#

thanks for help

#

see you later!

nocturne wyvern
#

Hello. Does anyone know how to adequately raise some part of the UI when the keyboard appears on the mobile (I enter text into TMP_InputField)? The issue is not the raising itself. But the question is how to determine the height of the keyboard on Android and raise it if this keyboard appears

sage latch
#

This```cs
t.position = new Vector3(1000, 10, 50);
Debug.Log($"Mesh Renderer pos: {t.position}");

#

Huh??

sage latch
#

yes

#

This is in start

nova leaf
#

simple question: if i want to have a sound when a bullet hits metal, and spawn spark particles, where do i put the code? not in the bullet right,

quaint reef
#

You could put that even in the bullet

quaint reef
nova leaf
nova leaf
quaint reef
leaden ice
nocturne wyvern
#

Does anyone know how to customize the appearance of the keyboard for text input in a field? So as not to write in this strange field

quaint reef
nocturne wyvern
marsh wadi
topaz plaza
#

I have a problem with OnMouseOver and using Colliders.
So I placed a BoxCollider in my Armature root (to ensure the Box Collider will adhere to the animation transformations).
The BoxCollider is a Trigger.
So when I hover over the GameObject now nothing happens.
When I put the BoxCollider at the same level as the GameObject where the Component is located of the OnMouseOver logic -> it works.

However there is one way I can make the BoxCollider work when it is placed in the Armature root. It works if I add a RigidBody component to the GameObject. Then for some reason OnMouseOver works with the BoxCollider no matter how deep it is nested in the GameObject's child hierarchy.

Can someone explain to me why that works? I find it not very intuitive.

latent latch
#

Can always do raycasting/raycastall and sort it all out easier with layering/tags/comparisons

cosmic rain
knotty sun
hallow coyote
#

I have a very large navmesh. How can I limit my navmesh agent to only a specific zone/area on the navmesh (so my enemies won't leave their area)? Do I need multiple navmeshes or can I somehow constrain an agent to an area?

cosmic rain
knotty sun
#

this is the old system but should still work with the new one, the old docs are much better to learn from

topaz plaza
signal moon
#

Just for the biggest competition in my school

#

With important members of many IT companies

#

But i dont think ill make it till then with overload of work from school

#

But well, 2 months left

nocturne wyvern
#

why can’t I press the normal send button when shifting?? Well, or maybe you can somehow remove Deselect and the disappearance of the keyboard when you tap on the send button

icy depot
#

Is there any magical component that I can store information (variables) in without making a whole script?

lean sail
icy depot
#

i was hoping an external single script could access the info stored in many gameobjects throughout my game's hierarchy

latent latch
#

make it

icy depot
#

will having many scripts affect performance? that's the only reason i was averse to it

latent latch
#

this isn't the 1980s

wicked scroll
icy depot
#

that's reassuring! i'll implement it immediately

wicked scroll
#

best not to worry about performance until it becomes a problem

icy depot
#

i guess that time i had 300 scripts, it was because of what they were doing that i froze

wicked scroll
#

yep, definitely

icy depot
soft shard
# icy depot i guess that time i had 300 scripts, it was because of what they were doing that...

If a script is a MonoBehaviour and has empty Update functions, or other Unity functions that are not used (assuming the script and object its on are enabled), this will affect performance, so as long as your 300+ scripts remain clean and only have code its actually using, and your not doing anything taxing in Update, you should be fine, having many scripts in general is a common workflow, and tends to happen with inheritance based programming as well

lean sail
soft shard
#

^ and for all your performance concerns, theres always the Profiler to track down those specific scripts, if its even script related (sometimes it could be related to rendering, physics, lights, etc, the Profiler can also catch that kind of stuff and even be attached to builds)

rancid frost
#

How to serialize Textures in a persistent manner?

icy depot
#

to know that unity can do so well with scripts is really reassuring!

knotty sun
rancid frost
knotty sun
#

yes but that is editor only

rancid frost
#

ok

#

How can i best save this with JsonUtility?

#

As it stance, Json Utility merely saves the instanceID (non-persistent)

knotty sun
#

you really do not want to save Texture data using JSON

rancid frost
#

Ok, it is recommended I use custom saving method for such things

rancid frost
knotty sun
#

is this procedural? in Editor? Runtime?

rancid frost
#

procedural..ish, its a 2d grid map. User will be able to stack textures* and sprites on one hex.

knotty sun
#

what does that have to do with serializing Textures?

rancid frost
#

I need to save the map

#

its a 2d square/hex map, made from sprites and textures at runtime

knotty sun
#

so the map is a Texture itself?

rancid frost
#

yes, the hexes are made up of a grass texture

knotty sun
#

well once you've made the map you do not need the source textures, you just need to save the map

rancid frost
#

yes, but the map can be modified

#

for example, the grass texture, might it turn turn to snow etc

knotty sun
#

so, when it changes you save it again

#

the other option is not to have the map as a texture but as a series of data points

rancid frost
#

yea, that is what Im doing

#

I was asking if the best strategy was just to save ALL textures in one Scriptableobject

#

then serialize them from there

knotty sun
#

but you dont need to do that, your source textures are already in your project

rancid frost
#

ok, then how do i access them in build?

knotty sun
#

several ways, you can have references to them in a MonoBehaviour or ScriptableObject or load them using Resources.Load

rancid frost
#

I see

knotty sun
#

none of that has anything to do with you serializing Textures

rancid frost
#

I had used Json.utitly, and it saved the instance ID

#

Im guessing, I need to make this class Monobehavior then

latent latch
#

Unless you're like doing graffiti and painting on the texture to create a whole new texture, but otherwise you're just looking at serializing IDs

rancid frost
#

ok

latent latch
#

don't serialize by instance IDs though as they change between runtime

#

usually just generate your own GUID, otherwise asset IDs

rancid frost
#

how do i get assetID?

#

it seems, i will have to generate my own

latent latch
#

It's better just to create a new ID honestly and make your own lookup table for them

rancid frost
#

ok

knotty sun
#

you don't even need to do that. if you have a ScriptableObject which holds a List of your source textures then you only need to serialize for each hex in your grid a position and an index into that List

latent latch
#

that sounds pretty good too

rancid frost
#

I know what I can/must do now
Thank you very much @knotty sun @latent latch

icy depot
#

just to confirm, Transform.GetChild follows hierarchy.. right?

#

or is it one of those random thingx

#

things

knotty sun
#

GetChild takes an index into the children hierarchy, so yes

icy depot
versed spade
#
    public GameObject previousPipe;

    // Start is called before the first frame update
    void Start() {}

    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(previousPipe.transform.position,currentPipe.transform.position);
    }

    void spawnPipe()
    {
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;
        previousPipe = currentPipe;

        GameObject newPipe = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint)), transform.rotation);
        newPipe.name = $"Pipe_{pipeID}";
        currentPipe = newPipe.name;
        pipeID += 1;

    }```

Currently trying to create a Pipe Spawner for my flappy bird game. I am trying to provide a new name that runs the format of `Pipe_{IDNum}`. Whenever one is made it is set to the currentPipe and the former one is set to the previousPipe. My problem right now is finding the distance between them in my update function. If I set it to anything other than a gameObject variable then it will error out. But anything different and it doesn't allow methods. I need it to, when running currentPipe.transform.Position, to give me the position of the current gameObject Pipe it saved? Is there a good way to fix my code to achieve this?
knotty sun
versed spade
#

hmmm. Am I able to convert the name to a GameObject somehow? Cause I need the name to call the object

knotty sun
#

newPipe is already a GameObject

versed spade
#

So just put newPipe itself there?

knotty sun
#

yes, that would seem obvious

#

your IDE should be highlighting this as an error. If it is not you need to configure it

versed spade
celest iron
#

Hi.
I have these functions for my player movement and for a knockback effect (yes, I will put the knockback for the enemy to deal, not the player in a later time).
https://pastebin.com/zjDRqH5U
It works fine, but I feel like this is a cheap solution

if (isHit)
        {
            rbody.velocity = Vector2.ClampMagnitude(rbody.velocity, maxSpeed + 5);
        }
else
        {
            rbody.velocity = Vector2.ClampMagnitude(rbody.velocity, maxSpeed);
        }
isHit = false;

I need this otherwise the knockback will be clamped to the max velocity when moving. Is there a better way to do this?

#

If I ever want to have different knockback forces, this solution would actually be a pain

steep herald
#

@celest iron If it works as intended, then maybe don't overthink it.

It's hard to give feedback if we don't understand the motives behind wanting to clamp your velocity. In theory, you're not supposed to manipulate velocities directly. You are supposed to tune your physics simulation so that you get the behaviour that you want with a combination of mass and drag values, along with adding proper forces.

That being said, game dev is game dev and the idea is to take a rocket to the moon. You can absolutely do what you are doing but you need to account for all potential bias without relying on the engine to do so for you, since like I mentioned, it's not designed with the idea that you'll manipulate the velocities directly.

If you want to have different knockback forces, then yeah, manipulating velocities directly is taking the highway towards a headache.

celest iron
#

But how am I supposed to clamp the velocity to a max velocity then?

#

Otherwise it will just fly away

steep herald
#

Then the forces applied relative to the mass and the drag you are using are likely very unrealistic

celest iron
#

Well, using linear drag did seem to be better

spring flame
#

Is there a way of suppressing unity from drawing a certain transform gizmo? I am particularly interested if I can draw a custom gizmo for scale if there is some specific component added by me

latent latch
#

disabling the object will do it

#

so adding the gizmo script on an independent object if you don't want to affect the actual object

#

or rather I guess you can just disable it as a standalone component

quaint rock
#

could setup your own EditorTool, that has its own handle drawing

latent latch
#

oh im reading this wrong. Yeah, you can disable transform tools pretty easily

#

via editor script

quaint rock
#

can also be used to override the build in tools

urban lintel
#

is there a way to make the trail renderer be relative to the size of the sprite without code, or should i be putting it in a script

#

it seems to be too wide by default, and if i change the scale of the object, it seems to remain the same

mossy minnow
#

hey everyone, so i have some weapon sway and im now trying to get aiming down sights to work. The problem is, when i try to aim down sights the gun becomes very jittery and glitches around. Anyone know why this might be happening?
wpnPos = restPos;

    void CalculateWeaponPos()
    {

        leanMove.x = leanMoveAmount * movementController.inputLean;
        leanMove = Vector3.SmoothDamp(leanMove, Vector3.zero, ref leanMoveVelocity, leanMoveSmoothing);
        newLeanMove = Vector3.SmoothDamp(newLeanMove, leanMove, ref newLeanMoveVelocity, leanMoveSmoothing);

        movementMove.x = movementMoveAmount * movementController.inputMovement.x;
        movementMove.z = movementMoveAmount * movementController.inputMovement.y;
        movementMove = Vector3.SmoothDamp(movementMove, Vector3.zero, ref movementMoveVelocity, movementMoveSmoothing);
        newMovementMove = Vector3.SmoothDamp(newMovementMove, movementMove, ref newMovementMoveVelocity, movementMoveSmoothing);
        wpnPos += newLeanMove + newMovementMove;
    }```
```cs
void CalculateAim()
{
    var targetPosition = Vector3.zero;

    if(movementController.isAiming)
    {
        targetPosition = movementController.camHolder.position;
    }
    weaponAimPos = Vector3.zero;
    weaponAimPos = Vector3.SmoothDamp(weaponAimPos, targetPosition, ref weaponAimPosVelocity, aimingInTime);
    wpnPos += weaponAimPos;
}```
#

and after that i just do transform.SetLocalPositionAndRotation(wpnPos, Quaternion.Euler(wpnRot));

#

nvm, i got it. shouldnt be setting weaponAimPos to zero every frame lmao

unreal temple
unreal temple
#

But yes, that is obviously wrong in your code haha

#

Sometimes having multiple objects makes things a bit easier to reason about

heady iris
#

I use it to figure out how to move a parent so that a child winds up with a specific position and rotation

robust elk
#

Is there anyone who have any experience with abstract classes??

robust elk
# leaden ice https://dontasktoask.com/

So I have an abstract which called base and have three scripts which derived from it, so i make a list of the abstract base, but i don't know how to called a specific script in the base list..

I hope you understand what i mean

leaden ice
#

Back up and explain what you are trying to do.

#

And how you are trying to do it.

#

What you are asking about is possible but likely not the best or cleanest way to do things, and kind of defeats the purpose.

robust elk
#

I'll try to explain it i a better way

#

For example I have the base

Public abstract class base : monobehavior
{
// base
}

And there's a bunch of scripts derived from it

Public class A : base
{
srting name = " cat";
int index = 1;
}
Public class B : base
{
srting name = " dog";
int index = 2;
}
Public class C : base
{
srting name = " fish";
int index = 3;
}

And then there's a manager scripts
Which has a list of A,B and C scripts

Public class manager : monobehavior
{
Public List<base> bases;
}

So my question should be, am i able to get the value from the script B using foreach loop, or even remove the B script from the list

leaden ice
#

you should not be defining "name" and "index" separately on each child class

#

it should be like:

public abstract class Animal {
  public abstract string name { get; }
}

public class Fish : Animal {
  public override string name => "fish";
}```
#

then you can access name from your base class references

robust elk
#

Each scripts has its own methods and values, and i want to access these value, am i able to, or am i using the abstract in a wrong way

leaden ice
#

You are using abstract in the wrong way if you want to access something that is not common to all of them

#

why do you want to access them?

#

What will you do with that information?

#

The concrete reality of what you're trying to do is important, we cannot gloss over it

#

It sounds like you are trying to do things in the wrong place.

hard viper
#

i’m not sure. in this case, he just isn’t using the part where it’s abstract, because the abstract class has nothing

#

the point of an abstract class is to have an implementation that is common to all children, and/or define fields common to all children

#

but if your abstract class is empty, you aren’t doing anything.

robust elk
hard viper
hard viper
#

public interface IMyInterface{
public string name {get; }
public int index {get; }
}

#

then they all implement IMyInterface, and define a property instead of a field

#

public class A : IMyInterface {
public string name => ā€œdogā€;
public int index => 1;
}

#

but idk what you want to do exactly

robust elk
grave mango
#

Hey guys. Im drawing some random lines now and im wondering if there is a way I can try and retry this random algorithm without running the game? Its so slow on my macbook and takes a long time to run the game

latent latch
#

Can execute in editor but ideally make yourself a new project if the current one takes too long to start up

somber nacelle
#

Or just create a button that reruns it

nocturne wyvern
#

Hello

Maybe you know how you can block Deselect from the input field when you click on some buttons, so that the keyboard does not hide?

#

I was thinking of doing something like this crutch filtering

#

and in filters check EventSystem.current.currentSelectedGameObject

#

but in this case I always have inputfield in currentSelectedGameObject

royal wigeon
#

I've made a tilt script, and it works, but it doesn't tilt relative to the player's rotation, how would I fix it? It only works if I look straight forward on the X, but not in between.

#

This is all the code that makes it work.

quiet ferry
#

its the positon/ distance between the object checking that makes it lag
my object pool aswell that links with the spawner

tawny elkBOT
quiet ferry
#

could anyone help with optimisation? i just cant figure anything out even with AI.

fervent furnace
#

freeze for second?

quiet ferry
#

did the video i sent work?

#

ill send in different format

fervent furnace
#
do{
   randomPosition = Random.insideUnitCircle * spawnRadius;
} while (randomPosition.magnitude < innerRadius);
do{
  int val=random.range(0,100);
}while(val<10);
quaint rock
#

yeah those loops, make no sense

#

and all it will do is cause things to lockup

fervent furnace
#

btw when the game freezes for second? in which method?

quaint rock
#

like i think they are trying to get a random point in a ring instead of just a radius

#

but there are much better ways to do that, that do not involve looping till it just happens to be right

quiet ferry
quiet ferry
quaint rock
#

you first get a random direction with Random.insideUnitCircle

#

then you multiply that by a number, you get from Random.Range(minRadius, maxRadius)

#

boom random point betwene 2 radiuses no loop

fervent furnace
#

how large the spawnedPositions is?
btw you can use physics system to query a point, dont iterate a set of points without any space partitioning

latent latch
#

while loop bad

quaint rock
#

alos yeah way better ways to do is valid position too

#

and even if doing it that way dont comapre distance but use sqrmagiutude

#

persnally i would use the phyiscs system

#

got your check circle and check sphere methods

quiet ferry
#

i should have put this in code beginner or maybe im over tierd lol. so i need to get rid of the loop and use circle radius checks?

hard viper
#

why can TryGetComponent be called as TryGetComponent<MyMono>(out MyMono x) with or without <MyMono> type argument?

mossy gust
#

do you guys have an idea of how i could make an editor for my rhythm game?

somber nacelle
simple egret
mossy gust
simple egret
versed spade
#
    public GameObject previousPipe;

    // Start is called before the first frame update
    void Start()
    {
        spawnPipe();

        
    }

    // Update is called once per frame
    void Update()
    {
        if (currentPipe == null || previousPipe == null) { return; }
        float distance = Vector3.Distance(previousPipe.transform.position,currentPipe.transform.position);
        Debug.Log(distance);

        if (distance > distanceFromLastPipe)
        {
            Debug.Log("Pipe's are far enough for another to spawn!");
            spawnPipe();
        }
    }

    void spawnPipe()
    {
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;
        if (currentPipe != null)
        {
            previousPipe = currentPipe;
            Debug.Log(previousPipe);
        }

        GameObject newPipe = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint)), transform.rotation);
        newPipe.name = $"Pipe_{pipeID}";
        currentPipe = newPipe;
        Debug.Log(currentPipe);
        pipeID += 1;

    }```
I was hoping to get some feedback on my code here. I am trying to get a pipe to spawn when they are 50 apart in the x direction. Currently I am finding that distance based on the object that was the previous pipe and current pipe. My problem is spawning in the pipes in the first place. I can easily get the first pipe to spawn in but the second one doesn't work with my update loop. Is there a better way to design this? Or should I keep it and add a line that finds the distance of the right hand side of the main cam to the pipe set in currentPipe to find when I need to spawn a second one. for the start program
chilly surge
hard viper
#

ty guys

#

also, is there a quick way (like O(1)) way to truncate a list? Like RemoveRange, but I actually just want to effectively assign a smaller .Count?

rain minnow
lean sail
#

Although that introduces complexity

hard viper
somber nacelle
#

then just use RemoveRange

hard viper
rain minnow
#

But an O(1) wouldn't make sense if there are multiple elements to remove . . .

little meadow
#

you can obviously implement your own list

late lion
hard viper
late lion
hard viper
#

i see

rain minnow
lean sail
#

Sounds like pre pre mature optimization. You arent getting a better method that does magic here

late lion
#

The Array.Clear isn't strictly necessary for value type Lists, but definitely necessary for reference types, so there isn't a hanging reference preventing the objects from being garbage collected.

hard viper
hard viper
rain minnow
#

But even if you decrease the count, the previous memory is still in use if the Capacity is beyond a certain threshold. You have to use TrimExcess to reduce it . . .

late lion
#

I don't think memory is the main concern here

deft dagger
#

hey i want to upload my game on play store but the aab file needs to be less than 200mb, i think i need to use play asset delivery to lower the size of my game but i dont know how. does anyone have any idea how to use it ? or if not is there any other way to lower the size of my game to 200 mb, right now its like 1gb or something, i did some compression but it wasnt enough

latent latch
#

wat 200mb

#

meanwhile itchio giving you that whole gb

#

best advice, texture atlases

late lion
#

itch.io doesn't need to worry about 3rd world internet like Google Play does.

somber nacelle
#

unfortunately itch does have to worry about 3rd world internet. at least for webgl games cry
I ran into an issue where i had a file in my webgl zip that was 233mb when uncompressed and itch wouldn't play it

#

of course that really only applies to webgl games, but they do still have a 1gb limit for uploads

frosty sequoia
#

trying to change the amount of particles emitted per second in runtime but these 2 lines of code dont work? this seems right to me and idk what else it could be. does anyone know how to fix this?

somber nacelle
#

are you certain this code is running? and that you are referencing the particle system you are attempting to change?

wicked scroll
somber nacelle
wicked scroll
#

oh nice, was that an old thing?

somber nacelle
#

it's been like that as long as i remember šŸ¤·ā€ā™‚ļø

scarlet kindle
#

hey do you know where i can clear my project & gi cache manually? like where it's located in my system files?

I was editing a prefab instance, and my editor crashed, and now it wont start. I believe clearing the cache might fix the issue but not sure where it is and which files are safe to remove

narrow summit
#

Is there a dumb way to not invalidate package cache for a particular package [it is my own package]? [without copying it somewhere else or into local]

somber nacelle
#

you can avoid invalidating the package cache by not modifying the package. otherwise you need to embed the package in the project if you want to modify it

narrow summit
#

meh. why is there not an easy way to load assets in editor outside Assets !! Packages was one hope, but that seems to trigger a package cache invalidation

scarlet kindle
#

is it safe to delete %LOCALAPPDATA%\Unity\cache ?

knotty sun
#

no

scarlet kindle
#

maybe restarting will help...

#

T_T

#
    Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================

=================================================================
    Managed Stacktrace:
=================================================================
      at <unknown> <0xffffffff>
      at UnityEditor.SceneManagement.EditorSceneManager:LoadLastSceneManagerSetup <0x00086>
      at UnityEditor.EditorApplication:Internal_RestoreLastOpenedScenes <0x001ea>
      at System.Object:runtime_invoke_void <0x00084>
=================================================================```
#

im attempting to install a newer version of the editor, but i suspect it won't fix it...

#

since it probably shares same cache

heady iris
#

consider deleting the Library folder in the project

#

it's built from your assets and also caches stuff like shader variants

#

Deleting it will require a full re-import of all of your assets.

scarlet kindle
wicked scroll
#

do what fen said (and remember that anything you are afraid to delete, you can make a backup copy of first)

scarlet kindle
#

ok thanks, will try

heady iris
#

If the problem persists, then you can try bumping the editor version

#

that is, the newest minor release

#

if you're on 2022.1.2, you can go to 2022.1.3, 2022.1.4, etc.

#

x.y.z -> change z, don't change x or y

scarlet kindle
#

ok so, it loads now, until I try to open the offending scene

#

and then the same crash happens

#

so, i think the prefab somehow got corrupted in that scene? not sure

simple egret
#

That's what one thread says online, when I search for the error message. Inspect the logs, on their end there was a syntax error in a YAML file (asset file format) which caused the crash on load

scarlet kindle
#

Hmm...~~ the interesting thing is the prefab I was editing doesn't appear to be in my Asset library anymore~~
Edit: this appears to be wrong looking at my source control history

brisk plaza
#

Hi

#

Whenever I try to install my app, it says 'App is not compatible with this version'

#

No errors in console, nor when testing in unity

somber nacelle
brisk plaza
#

Then I saw someone else already did before 🤣

somber nacelle
#

hey if you want to misuse channels and be obnoxious that's on you šŸ¤·ā€ā™‚ļø
maybe we'll get lucky and a mod will mute you. in the meantime though perhaps you should read over #šŸ“–ā”ƒcode-of-conduct

scarlet kindle
#

might help

somber nacelle
brisk plaza
#

ok thats a no

#

alr ill shut up now

somber nacelle
#

yeah you can stop pinging me now. you're being incredibly obnoxious

simple egret
scarlet kindle
#

I'm wondering if it's smarter for me to just revert to my last commit and try to work from there... clearly one of my files is corrupted, not really sure which one at this point

heady iris
#

Ah, you're using version control!

#

you could diff the scene file and see what has changed

simple egret
heady iris
#

You could just check out the scene file, yes

#

git checkout filepath

heady iris
scarlet kindle
#

Idk why my brain isnt working, this is so obvious xD

dense tapir
#

Hey guys?

Anyone have a script for enemy spawn?

Like...

  • Amount of enemys to spawn
  • spawn radius
  • check if them died to spawn again
  • give them rigidbody
  • give them mesh collider
  • give them other scripts (like my enemyAI or enemyStats)
heady iris
#

just spawn prefabs

somber nacelle
dense tapir
dense tapir
dense tapir
latent latch
#

enemies prefabs and SO and script for spawning

somber nacelle
simple egret
# scarlet kindle Idk why my brain isnt working, this is so obvious xD

If all else fails, you could dive into the EditorPrefs to try and change the last opened scene path.
Since the code is open-source you can clearly see the loading logic:

  • Retrieve the last opened scene path from EditorPrefs (that's probably located somewhere on your computer)
  • If the path is valid, try to open that scene and report errors as needed (execution does not take that path in your case)
  • If the path is invalid or empty, load the last opened scene (you get the exception there)
    So you could technically at least open your project by providing a valid scene path in the editor prefs before booting Unity up.
    The method: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/EditorApplication.cs/#L551, exception occurs on line 584.
dense tapir
#

here is place to ask for help and i just ask for help so what is your problem?

somber nacelle
simple egret
scarlet kindle
simple egret
#

Yeah post the log in a paste website, maybe there's something in it!

dense tapir
somber nacelle
#

i'm not asking for someone to build my game for me
yes, i asked someone to build my game for me

scarlet kindle
simple egret
dense tapir
somber nacelle
simple egret
scarlet kindle
dense tapir
simple egret
#

See if you can search the log file for "syntax", "asset", "invalid". The forum link I posted has the error at the end of the thread, maybe you should search for some of these keywords

somber nacelle
lean sail
dense tapir
#

ooh man...always these little kids...come on, go back to the sandbox to play if you want to weigh every word instead of helping...which is what the channel is intended foršŸ¤·ā€ā™‚ļø

knotty sun
lean sail
knotty sun
#

we know the difference. Do you?

simple egret
#

The little green icon aside their name really indicates that they clearly don't know how things work here, but yet they try to teach people that have been here for years how to help. Great initiative, but as I said it doesn't work like that

scarlet kindle
#

If I could get more info to find the specific asset in question, that would definitely help

simple egret
#

Try a search for "unable to parse" altogether or any of these words alone

scarlet kindle
#

I guess another solution would be just reset entire project back to last commit

simple egret
#

Make sure your search is case-insensitive also

scarlet kindle
#

i wont lose much to just go to my last commit... i think i'll just go with that

simple egret
#

Yeah do a checkout on the specific commit before reverting it

#

Each one is assigned a hash, so git checkout <hash> will get you to a specific commit, and git checkout master (or whatever branch is your current) will take you back

#

If it loads properly with that earlier commit, you can then do a diff between the two to see what changed

scarlet kindle
#

i did git checkout <hash> its still crashing

#

possible new files could be made that are crashing it?

#

that werent in the last commit?

#

let me try deleting those new files

simple egret
#

Yeah I think that if you have untracked or modified files, it will keep them even when you checkout another branch/commit so you don't lose your modifications

scarlet kindle
#

right

simple egret
#

So yep if you remove those files and it works again, the fault was in one of the untracked/new/modified ones

hard viper
#
public static void CleanList<T>(List<T> rawList, Comparison<T> comparer) {....}
public static void CleanList<T>(List<T> rawList) where T : IComparable 
    => CleanList<T>(rawList, T.CompareTo);```
This doesn't work, but I'm trying to automatically reference the CompareTo function that must be defined in an IComparable. How do I do that?
scarlet kindle
simple egret
#

Yep, see if it also happens in a new, blank project to rule out an Editor issue

latent latch
scarlet kindle
#

the other scenes in the same project load fine :/ so it's definitely something with the assets in that scene, but yea i'm probably not being thorough enough to figure it out, even with the git logs and stuff

#

i'll just pull the project fresh from the repo

#

that should work, otherwise i'm out of ideas

hard viper
#

lambda worked great. good idea. ty

#

idk if it's actually a direct ref, if compiler is smart enough

#
    => CleanList<T>(rawList, (x,y)=>x.CompareTo(y));```
I guess I'm wondering if the compiler is smart enough to optimize this
#

or if it tries to make a whole new Comparison<T> object every time

simple egret
#

I guess you could pull the default comparer for T and pass that to the underlying method: Comparer<T>.Default
It's smart enough to detect whether the type implements IComparable (why not use the generic IComparable<T> instead?) and to return a comparer that uses it

hard viper
#

I see. I changed it to the generic version

chilly surge
#

IComparable.CompareTo is also an instance method so T.CompareTo doesn’t make sense either. But even if it did exist, Unity’s C# is not new enough for that feature.

hard viper
#

I know it doesn't make sense, but idk how to get a direct ref to that function, instead of making a lambda that does the same thing

#

I guess it wouldn't be the same, right? I just realized

chilly surge
#

Too bad we don’t have it.

hard viper
#

it's not like a huge deal. just looking to learn

simple egret
#

Yup "static abstract" members in interfaces (the thing that can make an interface force the implementation of a static member) is only available for roughly the latest versions

hard viper
#

i'm mad we don't have all the interface functionality

#

virtual methods and protected members and all that

#

and please don't say it's a bad pattern. I just want it

chilly surge
#

Being stuck at C# 9 in Unity while looking at all the shiny new toys in regular .NET projects gives me feelings šŸ˜”

hard viper
#

my garbage collector needs to retire

#

that man has been working the shittiest job for years

#

and people only complain about how slow he is

#

give the man a break

cold parrot
#

If only I had c# 11, I could finally release a game.

scarlet kindle
#

Thank god for Github. @simple egret worked with the nuclear reset fortunately

#

might be a good time to upgrade my Editor since there's definitely bugs with this build..

scarlet kindle
#

lol

#

the exact same action as before

#

made the exact same crash

#

i am the definition of insanity

twilit scaffold
#

just a PSA:

frosty sequoia
forest ravine
#

Hello, does anyone know if Camera.projectionMatrix returns correctly if the camera is orthographic?

#

Ok, yes it does

#

Mistake of mine (matrix compositon occurs from right to left)

#

(in unity)

muted schooner
#

Hi folk! What's your approach on interface assignments through inspector? I know there are multiple solutions, but which one do you prefer? As you may know, you can't assign values to interface variables through inspector by default

wicked scroll
hard viper
#

TNRD made one on openUPM

wicked scroll
hard viper
#

oh look, it’s exactly what he wanted

umbral acorn
#

Hey guys! I have a question. How can I match a GameObject's size to the Physics.OverlapSpere's radius? I am making a Tower Defense game and one tower has an ability that when you click a button it freezes enemies that are inside the radius. I couldn't find a way to show the radius to the player. I can use OnDrawGizmos method for debugging but I'd like to show the radius during the gameplay to the player. Thanks in advance!

oblique barn
#

is anyone able to see whats wrong with this script? its supposed to be able to add cubemaps on objects as shaders but it doesnt work (i didnt make this someone else did and sent it to me)


public class AddCubemap : MonoBehaviour
{
    public Cubemap cubemap;

    void Start()
    {
        if (cubemap != null)
        {
            Renderer rend = GetComponent<Renderer>();
            if (rend != null)
            {
                Material mat = rend.material;
                if (mat != null)
                {
                    mat.SetTexture("_Cube", cubemap);
                    mat.shader = Shader.Find("Skybox/Cubemap"); // Set the shader to use cubemap
                }
                else
                {
                    Debug.LogWarning("Material not found on this GameObject.");
                }
            }
            else
            {
                Debug.LogWarning("Renderer component not found on this GameObject.");
            }
        }
        else
        {
            Debug.LogWarning("Cubemap not assigned to the script.");
        }
    }
}
clever iron
#

Can someone tell me why my update function isnt working?

somber nacelle
#

you cannot yield inside of a method that returns void

clever iron
#

ah

#

thanks

plucky dagger
#

This is a script I found online for a realisitic car controller, I've been reading through it to understand how it all works, but, I can't figure out how the hell its getting input from the keyboard to know what to make the car do. They did say they use the old input system, but I'm unsure what that is or what to look for in that case

https://hastebin.com/share/liligidejo.csharp

#

Moved to code-beginner as I feel this is the wrong channel

ashen jasper
#

is there a way that I can set a path based on the area the character is in

#

I'm basically making my character loop around a path and if in a part of the path is interrupted it will reset based on the path coordination

#

this is a photo of it

cosmic rain
ashen jasper
#

The loop

#

Better if i try to draw it

cosmic rain
#

What? "Cool it"?

How are you moving the character?

ashen jasper
#

Im moving the character via the x and y position with physics applied

#

The z position is always at 0

#

At start

cosmic rain
#

So how are you making it follow the path?

ashen jasper
#

Im not

#

Just x and y is moving

#

This is just me testing the collusion

cosmic rain
#

You said:

I'm basically making my character loop around a path
ashen jasper
#

Oh I wrote that wrong

#

I'm basically trying to make my character loop around a path and if in a part of the path is interrupted it will reset based on the path coordination

#

MB

cosmic rain
#

Okay. So, you'd need to define the path somehow

ashen jasper
#

Yea when he gets to the loop

#

At least in the area I highlighted

cosmic rain
#

With waypoints for example. Or bezier curves. And if it's interrupted, you just sample the closest position on the path and return it to it

ashen jasper
#

Do you have a example of this

cosmic rain
#

No. But there isn't really much to example.

ashen jasper
#

Well let me try

cosmic rain
#

But the exact implementation would depend heavily on your project context.

keen smelt
#

Hi team. JOB question. I have a RayCastCommand job. If I complete it in the update loop after scheduling the batch, all good. But if I wait until the LateUpdate to complete it, I start getting some "Native Array deallocated" errors. It should be the same frame, no? Any advice here for what I'm messing up?

#

and I'm not disposing the native arrays until after I complete the job.