#archived-code-general

1 messages · Page 192 of 1

steady mountain
#

I'm having a problem with my VTOL rotation script:


Vector3 rotationTorque = new Vector3(-mouseY * mouseSensitivity, mouseX * mouseSensitivity, 0);
Vector3 currentRotation = VTOLBody.transform.eulerAngles;
currentRotation.z = 0;
VTOLBody.transform.eulerAngles = currentRotation;
rb.AddRelativeTorque(rotationTorque);

if (Input.GetKey(KeyCode.Space))
{
  rb.AddForce(Vector3.up * vtolForwardSpeed, ForceMode.Force);
}
if (Input.GetKey(KeyCode.LeftShift))
{
  rb.AddForce(-Vector3.up * vtolForwardSpeed, ForceMode.Force);
}

Vector3 moveDirection = VTOLBody.transform.forward * pitchInput + VTOLBody.transform.right * rollInput;
moveDirection.y = 0;
moveDirection.Normalize();
rb.AddForce(moveDirection * vtolHoverSpeed, ForceMode.Force);

Debug.DrawLine(VTOLBody.transform.position, VTOLBody.transform.position + VTOLBody.transform.forward * 15f, Color.blue);```

The rotation for the body stutters with the more I move the mouse. Rb is set to interpolate and this code is inside FixedUpdate(). I'm assigning mouse input inside Update()
#

hierarchy looks like this

heady iris
#

What is VTOLBody ? vtol in the hierarchy?

steady mountain
#

Yes

heady iris
#

Does it change if you remove the bit that sets the transform's rotation direectly?

#

the fourth line in that snippet of code, specifically

steady mountain
#

It does seem to improve

#

How else can I clamp the Z rotation?

heady iris
#

Setting the rigidbody's rotation instead of the transform's might help

steady mountain
#

Should I clamp it inside update() or FixedUpdate() though?

heady iris
#

I don't know how rotation gets interpolated

#

setting it in FixedUpdate seems like the right thing to do

#

(but that might wind up looking stuttery)

celest iron
#

Any Rigidbody rotation is handled in FixedUpdate, this includes Rigidbody.Rotate and Rigidbody.MoveRotation.

steady mountain
#

Should I also assign mouse input inside FixedUpdate()

celest iron
#

For the new input system it doesnt matter

#

For the old, it will look jittery

heady iris
#

I can see some problems happening if you're reading mouse delta in Update and using it in FixedUpdate

#

if you get two frames before the FixedUpdate, you'll lose the first frame's deltas

#

so you might want to sum them up in Update and then reset the total to zero in FixedUpdate

steady mountain
#

The issue seems to be with the VTOL's range of rotation and how it indirectly results in roll in the aircraft. My stuttering was coming from my existing code trying to apply roll but the clamp wasn't doing a real-time job

#

Still can't figure out how to clamp it without stuttering though

whole portal
#

Having trouble with seamless chunk alignment in my Unity terrain generator using HLSL for marching cubes. Noise offset is set based on world position, but chunks still don't align. Anyone faced this before or have suggestions for debugging?

I can share my noise generation code if anyone wants to have a look.

heady iris
#

I'd be diagnosing this by visualizing the noise coordinate. Maybe make the terrain height be just the noise coordinate's X value

celest iron
#

By ends I mean the chunk borders

whole portal
#

Debugging right now guys. Will come back with the results, thank you very much.

#

Here are the logs.

whole portal
#

Should I debug this as well to make sure that's the case ?

celest iron
#

It wouldn't hurt

heady iris
#

where do you use the noise offset?

upbeat roost
#

Hello Guys,
I am working on a 2D Game and currently I want to detect some corners of a tilemap Collider. (see picture) Is this possible via code? and How? A general approach will also help.

whole portal
#

I've added debugging blue spheres which represent the corner of each chunk and its outline.

#

That's what I've got.

whole portal
# heady iris where do you use the noise offset?

The NoiseOffset is used in my GenerateNoise function in my NoiseCompute.compute HLSL shader. Specifically, it is added to the pos variable that determines the position where the noise is sampled. Here's the relevant line:

float3 pos = (id * _NoiseScale) / (_ChunkSize - 1) * _Scale + float3(_NoiseOffset.x, 0, _NoiseOffset.y);```
The NoiseOffset is meant to align the noise sampling across different chunks. Each chunk's noise is generated based on its position in the world, and NoiseOffset helps in shifting the noise function to align with that world position.

In my C# code, I set this offset based on the transform.position of each chunk:
```csharp
Vector2 noiseOffset = new Vector2(transform.position.x, transform.position.z);```
And I pass this to the shader:
```csharp
NoiseShader.SetFloats("_NoiseOffset", new float[] { noiseOffset.x, noiseOffset.y });```
So, the NoiseOffset is being used to ensure that the noise generation starts at the appropriate world coordinates for each chunk, aiming to make the noise seamless across chunks.
heady iris
#

NoiseOffset isn't affected by scale. That sounds suspicious.

#

although I also don't really understand what's going on in that first line in general

whole portal
#

Which one ?

heady iris
#

float3 pos = ...

#

id doesn't sound like a float3 to me, so that's weird

still carbon
#

Is there any way to tell what's chewing up memory in Unity? I've disabled everything in my scene - and restarted the editor so that everything was already disabled upon initial load - and the memory usage is still increasing at a pretty constant rate. If I let it sit for a day it'll go from a couple of gigabytes to north of 50.

heady iris
heady iris
#

(or just convert a local-space position to world-space and not even need a noise offset)

whole portal
# heady iris The entire line doesn't make sense to me. I would expect to see something where ...

In HLSL, the uint3 id provided by SV_DispatchThreadID can indeed be used in arithmetic operations with floats, but it may be a point of confusion if someone expects id to be of type float3.

The uint3 id is implicitly converted to a float3 during the arithmetic operations in the line.

  • id: This is the thread ID, which ranges from 0 to (_ChunkSize - 1) in each dimension (x, y, z). It identifies the point in the chunk grid that we are currently considering.
  • _NoiseScale: This scales the noise. Higher values will "zoom out" the noise, making it less detailed, whereas smaller values will "zoom in," making it more detailed.
  • _ChunkSize: This is the size of the chunk in the grid. It's the number of points along each edge of the cubic chunk.
  • _Scale: This scales the coordinates of the point. It's used to map the chunk grid to world coordinates.
  • _NoiseOffset: This is an offset applied to align the noise function across different chunks. It ensures that the noise function starts sampling at the correct world coordinates for each chunk.

(id * _NoiseScale) / (_ChunkSize - 1): This part scales the thread ID so that it ranges from 0 to _NoiseScale, rather than 0 to (_ChunkSize - 1). The scaling depends on the chunk size and the desired noise scale.

  • _Scale: Then we scale these coordinates further based on the _Scale factor.
  • float3(_NoiseOffset.x, 0, _NoiseOffset.y): Finally, we add the noise offset to ensure that the noise function starts at the correct position for each chunk.

This value of pos is then used to sample the noise function.

It's a quick summary generated by GPT, so not sure how 100 accurate it is.

heady iris
#

Ah, that's the thread ID. OK.

#

although, I feel like you should be summarizing your code, not chatGPT...

whole portal
# heady iris Ah, that's the thread ID. OK.

I followed a guide which only provided the foundation and I'm just adding on top of it, so not even I understand exactly how this works at the moment. What you see going on with chunk generation (And I have digging too) was added on top of that foundation.

#

Here is the outline of the scripts and shaders I'm using (excluding my digging script)

#

The chunk manager was something added by me on top in order to get infinite generation. It was not in the original guide.

whole portal
winged mortar
#

I think Ur talking to an AI @heady iris

#

As if he fed your answer into gpt

#

And got that answer back

heady iris
#

i would advise not using chatGPT to learn to program, for sure.

gray mural
#

Is it possible to make player select just one option here? (still gonna use Flags)

[Flags]
public enum ItemType
{
    Ground = 1,
    Wall = 2,
    Player = 4,
    Obstacle = 8
}

public ItemType collisions;
heady iris
#

it's going to wind up inventing code that's wrong in novel ways

heady iris
#

so you'd be using a TMP_Dropdown or something

winged mortar
#

"In HLSL, the uint3 id provided by SV_DispatchThreadID can indeed be used in arithmetic operations with floats, but it may be a point of confusion if someone expects id to be of type float3." Who's someone?

whole portal
celest iron
winged mortar
#

I think it is not just limited to that one response..

gray mural
heady iris
#

I think you would need a custom property drawer.

gray mural
winged mortar
heady iris
whole portal
winged mortar
#

I am sure I have enum dropdowns in my project, could try to find some code for it

heady iris
#

I haven't written compute shader code in a while (well, it was CUDA, but close enough), but I distinctly remember it leaving very little room for "i don't really know"

heady iris
#

apple wants the dropdown without the multi-select.

gray mural
celest iron
#

Well, I have absolutelly no idea how to work with shaders, but for normal terrain gen you'd need to give offset for each possible chunk neighbour

winged mortar
#

I don't think it has multi select?

#

Or is that added due to the flags attribute?

gray mural
#

we're talking about inspector

pastel patio
gray mural
winged mortar
#

Alright got it, didn't know flags would add a multi select dropdown, mb

celest iron
gray mural
celest iron
#

probably you forgot to add the chunk size somewhere

pastel patio
#

flags converts it to a layermask, something that looks very self explanatory if you look at it from the perspective of bytes

whole portal
gray mural
pastel patio
#

Yep, you can make a second enum with the same names to use as a single-option selection, it makes code look worse imo but it makes inspector a tad clearer, if it's worth it it's up to you lol

whole portal
#

@celest iron I may need to use offset. Trying to see if it fixes it.

celest iron
#

Good luck

#

Keep in mind tho I know nothing about shaders. I'm giving answers based on what I know, which is terrain gen.

celest iron
#

For thhe problems similar to this I've seen, most people were passing just the center of the chunk, so it wouldn't align with the borders OR passing only the final point/pixel as offsets, making it only align in the last vertex.

pastel patio
#

I've been having trouble with loaded&unloaded object compatibilities
(i) Unloaded version is just a struct with id, pos, rot, and extra data, loaded is monobehaviour based

Since a reference to another loaded gameobject can not be saved past a reset (Or call it a reload), I would have to keep the reference focused on the dataside, which is the side that always exists.

So I thought to make the data of every single object registered in a list, and all the data keeps their index in the list (public int instanceId)

However, any option I'm aware of would mess up with removing an element from the list, since any new object taking it's place after id would be mistaken by references to be the original.

Resolves I can think of so far:

Changing the structs to classes could be an option, maybe, idk if it could be destroyed and whether if it would set all references to invalid.

Another option I can think of is to make references subscribe to events that warn them about id reassignments and deletions, but I'm uncertain if this is a good idea, sounds like it could be dangerously expansive...
Unless if someone knows a whole better way to approach this problem? Sorry about making this a difficult read but I wanted to explain this problem from the bottom up.

Please ping if and when you reply, thanks!

rigid island
#

!code

tawny elkBOT
#
Posting code

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

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

rigid island
deft kindle
brisk grove
#

...

simple egret
#

Do not share screenshots of code unless requested, the server rules say

brisk grove
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovment : MonoBehaviour
{
   public float RotSpeed;
    public float Speed;

    public bool GAMEOVER;
    public GameObject GAMEOVERob;
    void Start()
    {
        
    }

    
    void Update()
    {
        transform.Translate(Vector3.up * Speed * Time.deltaTime);
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Rotate(new Vector3(0, 0, -1) * RotSpeed *  Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Rotate(new Vector3(0, 0, 1) * RotSpeed * Time.deltaTime);
        }
        if(gameObject == true)
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            GAMEOVER = true;
        }
    }
    public void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
#

hi Guys
i have a problem again
i dont know the wrong in the code
the code must show the "GAMEOVER" and restart buttom when the player collied with the Enemy but when i start the game the player got invisiable

simple egret
#

Nothing makes the player disappear here.
A common cause is that the script that makes the camera follow the player sets the camera's position to the player's position, thus putting them at the same Z position, rendering the player invisible

#

Make sure that when you play the game, the camera's position stays at Z -10

#

Or whatever you have initially in the scene

brisk grove
simple egret
#

Now while playing the game

brisk grove
#

oh

scarlet viper
#

would it be faster in runtime to store over thousand dictionary keys or to store just a hundred and interpolate/Lerp between them?

brisk grove
rigid island
brisk grove
#

it didint worked

rigid island
#

this will always be true

brisk grove
#

and?

rigid island
#

ur setting sprite to false

#

so it "disappeared"

simple egret
#

Welp so big I managed to not see it

brisk grove
#

what should i do

simple egret
#

"if this object exists, make me invisible" - This is always true

rigid island
brisk grove
simple egret
#

Set it to false elsewhere

brisk grove
simple egret
#

Probably when you enter in collision with the enemy

rigid island
#

why make it true on collision if ur not gonna use it

#

but yeah having it in update is overkill

#

just put it inside OnTrigger

brisk grove
#

ok i will try

#
 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            GAMEOVER = true;
        }
        if (gameObject == true)
    }

like this ?

simple egret
#

Well you only copied one line instead of the whole if statement

brisk grove
#

no

#

this is the whole if statmint

#

if (gameObject == true)

#

ohh

simple egret
#

No you forgot the whole block after it

brisk grove
#

yeah right

simple egret
#

The if statement is also not necessary

brisk grove
#
 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            GAMEOVER = true;

        }
        if (gameObject == true)
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);
        }

    }
#

?

simple egret
#

You can put the two lines inside the if (collision.gameObject.... one

#

if (gameObject == true) will always be true. When the script runs on an object, it exists

#

Perhaps you meant GAMEOVER == true?

simple egret
#

Seems like you need to !learn C#

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

gray mural
#

it's Component.CompareTag

simple egret
#

????

gray mural
#

Collider2D is a component

brisk grove
#

the gameover object must be visible when the Enemy collid with the player

brisk grove
gray mural
brisk grove
#

?

rigid island
gray mural
brisk grove
#

*I DIDINT UNDERSTAND *

simple egret
gray mural
#

and gameObject can never be null

#

gameObject == true is the same as gameObject != null

simple egret
gray mural
#

the same as if (true) in your case

brisk grove
#

so i should delet gameobject

gray mural
#

to be sure, you have to delete .gameObject

brisk grove
#
private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            GAMEOVER = true;

        }
        if (gameObject == true)
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);
        }

    }

like this?

gray mural
brisk grove
#

what SPR2 wrote?

gray mural
brisk grove
#

i mean where

gray mural
#

above ⬆️

brisk grove
#

can u reply it

rigid island
#

bruh

simple egret
#

Just scroll up

rigid island
#

I think one line would've sufficed..

gray mural
brisk grove
#

SPR2 — Today at 10:46 PM
You can put the two lines inside the if (collision.gameObject.... one
if (gameObject == true) will always be true. When the script runs on an object, it exists
Perhaps you meant GAMEOVER == true?
i didnt understod this

#

iam realy dumb
iknow 😶‍🌫️

gray mural
#

ok, now you can read other messages I have written after that

brisk grove
#

I'm really serious but where

gray mural
brisk grove
#
    {
        if (collision.CompareTag("Enemy")) && if (gameObject == true)
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);

        }
        
gray mural
rigid island
#

dude is just trolling at this point

brisk grove
brisk grove
#

no

brisk grove
rigid island
spring creek
gray mural
brisk grove
#

yes

rigid island
gray mural
spring creek
spring creek
rigid island
#

they dont go together

brisk grove
#

how
dont ban me plz

brisk grove
spring creek
gray mural
rigid island
#

😉 it happens

brisk grove
gray mural
brisk grove
#

no

gray mural
#

just read my messages above

brisk grove
#

ok

gray mural
#

solved UnityChanThumbsUp

brisk grove
#

no

#

not yet

gray mural
#

!csharp !learn

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
brisk grove
gray mural
#

!cdisc !learn

tawny elkBOT
gray mural
#

and !learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

gray mural
#

just one command per message ? 🤔

simple egret
#

Nah you can stack them usually

brisk grove
upbeat roost
brisk grove
#
    {
        if (collision.CompareTag("Enemy")) && (gameObject == true);
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);

        }
        

    }```
leaden ice
#

this makes me cry

brisk grove
#

like this
but ther 1 red error

rigid island
#

its ruff

simple egret
heady iris
#
if (...) {
  ...
}
#

if your code does not look like this, you will get an error

rigid island
#

cant believe this is still goingon..

autumn gorge
#

Yeah I also have it it in a bunch of other servers and still no answer. Would stack overflow work?

gray mural
main shuttle
torpid lantern
#

but only one liners

heady iris
#

yes, that's fair, but I'm talking about the case with a block statement

brisk grove
#
    {
        if (collision.CompareTag("Enemy")& gameObject == true)
        {
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
            gameObject.SetActive(true);

        }
        

    }```???????
heady iris
#

since that is what the user is trying to do

#

some invalid things:

rigid island
#

there is a bigger issue at hand..

brisk grove
#

ok

heady iris
#
if true { }
if (true) && (true) { }
if ((true)) && true { }
#

these are all malformed

torpid lantern
#

gameobject IS true if you're collidion isn't it?

gray mural
torpid lantern
#

I love bitwise!

#

bitshifting is my favorite!

rigid island
#

gameObject == true

still the wrong one

brisk grove
#

@gray muralthx evry 1

but the restart button didnt worked

rigid island
#
if (collision.CompareTag("Enemy"))
        {
            GAMEOVER = true;
            gameObject.GetComponent<SpriteRenderer>().enabled = false;
        }```
sleek bough
brisk grove
rigid island
rigid island
brisk grove
#

y

#

y not here

#

@rigid island?

rigid island
brisk grove
#

ok

modern creek
#

Getting some random editor/unity NREs in 2023.2.0b8 that I didn't see before.. any idea what these could be?

heady iris
#

resetting your layout might fix it

#

hard to say what, exactly, is breaking

modern creek
#

yeah I thought that too, I tried.. 😦

#

i tried also opening/closing presets folder, trying to get unity to rebuild it

#

I don't have any presets in this project, I don't think

#

🤷‍♂️

#

Ah, figured it out. Closing/reopening the Tile Palette window fixed it. No idea why.

#

Actually, no, just .. having the window causes the issues. I'll file a bug I guess

craggy sapphire
#

hey, so i know this isn't technically unity, but i still figured i'd ask here because there's lots of c# people; is there a way to get newtonsoft json into a project without dealing with nuget?

#

or, is there a way to recreate nuget without visual studio code?

heady iris
#

i just use NuGet for Unity to install NuGet stuff

craggy sapphire
#

...the whole point is not using nuget

heady iris
#

you said "without Visual Studio Code"

#

so I thought there was something specific there

#

there's a unity package that installs Json.NET

craggy sapphire
#

i'm not using unity either

craggy sapphire
#

is the thing

#

i kinda just needed c# help now and this was the only place i could think of

heady iris
craggy sapphire
#

yeah

heady iris
#

!csharp would be more likely to know this

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
heady iris
#

er

#

!cdisc

tawny elkBOT
craggy sapphire
#

thanks

rigid island
# tawny elk

they should swap the command for the server link, this snippet is so useless

simple egret
#

Yeah, doesn't even show what you need to do

sharp rose
#

Hello! I'm a newbie and I'm trying to implement a cool feature where everytime the character picks up a puzzle piece it displays an animation of it in the top left corner. I have a script that adds to a counter everytime a piece is picked up, I will take any advice or show any code if asked to, I could really use some help as this is for a game jam for Uni and I have limited time.

spring creek
rigid island
#

or i suppose being familiar with codeblocks from markdown

spring creek
#

Oh, you ONLY have the part that increments the counter

sharp rose
#

yea thats it...

rigid island
sharp rose
#

Am I taking on too complicated of a task for a beginner dev under time constraint?

spring creek
heady iris
#

I would do this in code.

sharp rose
#

Very little, I have set up an animation though that works at the moment

#

it displays the UI that I want in the top left

heady iris
#

You just need to position the puzzle piece in the right spot on the screen and make it do a little spin, or whatever

sharp rose
#

The top left icon is the UI and it represents when the player has picked up one piece of the puzzle

#

After you pick up two pieces I want the animation to change to a different animation where the puzzle has 2 pieces

heady iris
#

Ah, okay, that's different.

#

did you make a sprite with two pieces, or do you want to just show two pieces side by side?

sharp rose
#

I have animations for up to 5 pieces

#

or sprite sheets i guess

heady iris
#

sounds like you'd want to make an animator with five states in it, one for each piece

#

and just do animator.Play("3 pieces")

#

where one of the states is named "3 pieces"

sharp rose
#

does this require a script?

rigid island
#

almost anything requires a script:P

sharp rose
#

almost

earnest gyro
#

Unexpected OnColliderEnter Behavior

dense estuary
#

please, i still dont have a fix for this :(

bold pawn
#

That doesn't even link to one of your posts..

dense estuary
spring creek
#

You can even see their name in the reply link

soft shard
#

If your on mobile, maybe it didnt load correctly, though sometimes it just doesnt always scroll to the top of the post on desktop, at least it doesnt always for me

lusty timber
#

I'm having trouble displaying the velocity and speed of one my cars. the code I wrote works for one of them(currentCar=0) but doesn't work for the other(currentCar=1)

Both cars have rigid bodies and the scripts are applied to a Canvas
if needed i can provide the full code, i didnt want to flood the channel

heady iris
#

so you want the red square to be exactly centered on that gizmo?

#

you're just computing a size there, so I'm not really seeing where you're setting the square's position

dense estuary
heady iris
#

well, I don't know how the square works, so it's hard to say anything!

#

is the square centered on another gameobject, or is the square's pivot point on a corner?

dense estuary
#

i know how it works, it makes a grid and spawns a point in the grid. poisson disc sampling.

dense estuary
heady iris
#

looking at this photo again

dense estuary
#

its position isnt related to the position of the gameobject its script is assigned to, its position doesnt change when i move the object

heady iris
#

so what's even drawing the red square? is this a gizmo?

#

i don't know what you're doing, so it's very hard to give you advice..

dense estuary
#

it represents an invisible grid

heady iris
#

okay, so you want to position the grid cell such that its center is at a certain position

#

and you know the size of the grid

#

take the position you want the center to be at

#

subtract half of the grid size

dense estuary
#

my issue is the grid is made using an int array, and i cant use negative values.

heady iris
#

what do you mean that it's "made using an int array"?

#

you're going to have to show code.

dense estuary
heady iris
#

It's not intuitive at all that this could possibly cause an array to wind up with a negative index

heady iris
# dense estuary

i don't see how this has anything to do with offsetting the grid

#

this calculates the number of grid cells you need

heady iris
dense estuary
#

yes

#

sorry

#

I should've done that from the beginning, sorry.

heady iris
#

you should just compute all of the points normally and then offset them as needed

#

generating points in the local space of a specific Transform, then converting them from local-space to world-space, would probably be useful here

dense estuary
#

i think right now its generating the points in world space, how can i make it generate in local space instead?

heady iris
#

Just use transform.TransformPoint

#

Vector3.zero isn’t implicitly “in” a specific space

#

It depends on how you interpret it

#

If you do transform.position = Vector3.zero, you just used it as a world space position

#

transformA.position = transformB.TransformPoint(Vector3.zero)

#

this interprets it as a local space position for transformB

#

(i am going to bed, so I’ll have to get back to you tomorrow)

dense estuary
#

im seeing if i can move the points with a for loop

heady iris
#

but try generating random points in the range [0,0] to [1,1] and then seeing what happens when you use transform.TransformPoint to take them from local space to world space

#

see what happens as you position, rotate, and scale the object

fresh hull
#

Is it possible to do string interpolation like this?

loud wharf
fresh hull
quartz folio
fresh hull
#

🥲

#

time to make more enums then

noble lake
#

Hi everyone. Does anyone know how to render a RenderTexture over a mesh? Have to draw a bullet decal on wall collision, but have no idea how to do it using RenderTexture even after looking into it.

quartz folio
noble lake
quartz folio
noble lake
spring creek
#

That would require distance checking or some spatial query for each one though... so, that's suboptimal lol

noble lake
noble lake
whole portal
#

I'm working on a terrain generation system in Unity where the terrain is divided into chunks. The terrain generates seamlessly, but I'm facing an issue when I try to "dig" or modify the terrain at the boundaries between two adjacent chunks. When I dig at the boundary, the two chunks become separated and don't align properly.

Can anyone give me a hint of what to check for ?

swift falcon
#

Can anyone please help me with creating a grid that doesn't render behind walls? It's really ruining my game ngl

#

Pleasee I beg lol
I've been stuck with this for a while and unable to find anyone to help sad

quartz folio
swift falcon
#

I ask it here simply because I'm fine with remaking this grid if anyone has any suggestions

#
GL.Begin(GL.LINES);
cellMat.SetPass(0);
GL.Color(new Color(0,0,0,1f));
        
int xStart = (int)allocatedPosition.x * chunkSize;
int zStart = (int)allocatedPosition.z * chunkSize;
for (int x = 1; x < chunkSize; x++)
{
  // Line right
  GL.Vertex3(xStart,0.01f, zStart + x);
  GL.Vertex3(xStart + chunkSize,0.01f, zStart + x);
  // Line up
  GL.Vertex3(xStart + x,0.01f, zStart);
  GL.Vertex3(xStart + x,0.01f,zStart + chunkSize);
}
GL.End();```This was how this one is done
#

I don't know anything about shaders though so is the solution going to be writing a custom shader and using that as my material for the lines then? 😦

quartz folio
#

Does cellMat perform ztesting?

swift falcon
#

Shrug Doubt it, it's just one of the HDRP materials, let me go find it

#

Oh nvm it's a "GUI/Text Shader"

#

Is there any unity default shaders I can use for this?

#

I didn't think drawing some lines would be so hard tbh

#

Bing saved me 🙏 Praise Bing haha

#

@quartz folio Thanks by looking at zTesting I was able to get a shader, I've been trying to fix this for ages, much appreciated

short walrus
#

Has anyone used Astar pathfinding?

somber nacelle
#

also keep in mind that a* is an algorithm, if you are referring to aron granbergs a* project asset specifically you should probably mention that

short walrus
#

yeah the thing is, i want to see if someone has had the same problems as i have, for example i have a 2D game with a map with significant size, and i want a small part of it to re-scan paths. Because scanning the whole map lags the game. Ive looked around and people said to use multiple graphs, but in code, i cant find a way to isolate the graphs and separately scan them.

#

i could only reference the whole pathfinding astar game object which includes the pathfinding graphs. Cant find how to define the graphs separately

somber nacelle
#

this is for that asset i mentioned, yes?

short walrus
#

i dont remember exactly where i got it from, but it's "Astar Pathfinding" or A* pathfinding yes ill keep digging to find what version exactly it is

somber nacelle
short walrus
#

yeah that must be it

winged hull
#

how come the elif and else blocks gets grayed out in visual studio and have no intellisense?

somber nacelle
#

because that code is not being compiled

winged hull
#

is there a way i can make them not grayed out?

noble lake
knotty sun
winged hull
#

oh i see thanks

alpine sapphire
# swift falcon Can anyone please help me with creating a grid that doesn't render behind walls?...

if it is for play mode, regardless of how you created it, something you can do is use unity's URP system to create an effect that will not render your grid if it is behind object using this as a base tutorial, just inverse the logic : https://www.youtube.com/watch?v=szsWx9IQVDI

Let's learn how to render characters behind other objects using Scriptable Render Passes!

This video is sponsored by Unity

● Download Project: https://ole.unity.com/occlusiondemo
● More on Lightweight: https://ole.unity.com/lightweight

····················································································

♥ Subscribe: http://b...

▶ Play video
swift falcon
#

Tbh I might just downgrade to URP... HDRP just isn't worth it for the hastle it has been, it ends up looking worse

#

Thanks

alpine sapphire
#

np and good luck !

hoary monolith
#

how do you exclude the UI layer from post processing?

winged hull
#

how can i use .env for environment variables or something similar to that, so I can hide sensitive data like IP addresses from the code?

knotty sun
arctic spindle
#

Anyone here who managed to get an image to the clipboard? I keep getting errors when I try, I added system.drawings/forms to the unity project. "Failed to set clipboard: Requested Clipboard operation did not succeed."

halcyon dagger
#

Hey there, I'd like to create a grid for spawning players / objects

please find the examples attached.

Looking for an algorithmic approach to x number of players / objects

Any pointers? Much appreciated!

arctic spindle
halcyon dagger
#

ooh, nice idea, thank you

arctic spindle
#

It really depends on size tho

#

If you want to do it yourself

#

Easy approach would be to just use rows if you always have 1 or 2 in a row

#

if total %2 == 0, even, then it's just a for loop (total/2) CreateRow(2)
Uneven would be for loop, (total-1)/2, then at the end createrow(1) for the final row

arctic spindle
halcyon dagger
#

I would like to spawn up to 12 players (use case for now, potentially more later)

short viper
#

Do i need to pay unity for free games?

#

Please some one answer

leaden ice
knotty sun
#

why are you asking in a code channel?

urban lintel
#

im trying to set up an enemy behaviour that walks in a random direction, waits a bit, and then walks in a random direction again. I've done this in a coroutine, which im not sure if it's the best approach:

    private IEnumerator MoveRandomCoroutine()
    {
        Vector2 randomDirection;
        while (true)
        {
            float x = Random.Range(-1f, 1f);
            float y = Random.Range(-1f, 1f);
            randomDirection = new Vector2(x, y).normalized;
            movement = randomDirection;
            //wait for 2 seconds
            yield return new WaitForSeconds(1);
            movement = Vector2.zero;
            yield return new WaitForSeconds(2f);

        }
    }

Now i'm trying to extend the script so that if a player is in radius, it uses a different movement (walks towards the player for example). I've already written some code for detecting whether the player is in the enemy's radius, but struggling a bit to get it to switch between this Coroutine and the simple chasing movement. Should i just extract this out of a coroutine and handle the pauses with some normal timers in the Update loop? Or are coroutines fine and i should just pause one and start the other

main shuttle
urban lintel
#

will do, thanks!

worthy jungle
#

hello friends, I want to instantiate an UI image. I do that and and I set the canvas as the parent. it shows the imapge correct but the problem is scale! because it instantiates in the world first then it goes under canvas. how to solve this?

leaden ice
#
Instantiate(thePrefab, theCanvas.transform);```
worthy jungle
leaden ice
#

wdym by "didn't work"

#

what happens

worthy jungle
leaden ice
worthy jungle
worthy jungle
leaden ice
#

That would be in the inspector for your prefab's RectTransform

celest iron
#

Hi.
So I have a code that generates an island using noise and a seed, so far so good. I also have an UI button that calls the method to generate the island when I click on it so that I don't need to exit game mode when I want to change values for the generation.
The problem comes when I add a seed to the world gen: if I give the seed normally, outside of play mode, it work as intended. But once I give it (the same seed) on play mode and use the button to re-gen everything, I get very weird results.
The first image is when I give the seed outside of gamemode, the second is with the same seed, but using the button to regen the world. Because the land itself is the same, the problem is with the water tile I presume.
The water tile code: https://pastebin.com/nZG4CwqA
The island gen code: https://pastebin.com/h3z3gYWD

worthy jungle
leaden ice
#

where do you want it to be relative to the canvas, and where is it actually appearing?

#

and what are your RectTransform settings

worthy jungle
leaden ice
#

what matters is the RectTransform size

#

which is controlled by the anchors/offsets etc in the RectTransform

#

the scale you can ignore and should let the canvas scaler do its thing

worthy jungle
rigid island
#

dont crosspost mate

jovial moon
#

Sorry about that ^^

night harness
#

Don’t know the best way to ask this since it’s more theory based but anyone have insight into when you want to use scriptableobjects as the base of a data system but said system also has a unique class and/or script per scriptableobject? I have a few systems where SO’s fit the bill perfectly but I also have PlayerSkills, LevelChallenges and Equipment which all have a lot of reusable data where scriptableobjects work but I have to instantiate a specified type that’s specificed in the scriptableobject.

This in all would be gross but fine but lets say I wanted to have values in said unique scripts be in an inspector so I can easily tweak them. Now I’d be looking at a new scriptableobject type per scriptableobject just so i can manually specify these unique values

#

Im less looking for a specific answer and more vibes from people who have had to deal with thid

latent latch
#

Usually for scripts with a bunch of different assets I've a similar amount of scriptable objects that have a similar hierarchy for each type.

night harness
#

me too but in these scenarios every object in this type has unique data. They all still share some similar traits, enough to where I’d still wanna keep trying to use scriptableobjects for this but it just seems really gross to make a whole new scriptableobject type just so I can make 1 scriptableobject of said type

latent latch
#

Probably want to clarify what you're trying to create here

crystal birch
#

Or something like that

latent latch
night harness
#

it’s come up a few times but lets say my LevelChallenges

Level starts with x amount of them loaded and they all contain similar data like

ChallengeName
ChallengeType
ChallengeIcon
ChallengeDifficulty
ChallengeReward

Etc etc. and the way i track and load them is perfect for SOs. But the issue is each Challenge also has wildly unique code that needs to run during the level to actually track how these challenges are going. Which means 1 script and/or class per SO. But then if I wanted some of these unique things to have inspector tweakable variables then I can’t really do that in it’s SO because they are unique to each Challenge

latent latch
#

So give me some ideas what level 1 and level 2 would have differently from each other

#

because at this point you can do more of a composition approach if you're having problems trying to encapsulate more data

night harness
latent latch
#

meaning, just have what can be available between all levels on this script, if it's not to be used then simply ignore or hide it.

night harness
latent latch
#

there could be inconsistencies between some logic, but that's up to handling via checking, or simply dont append it together on the SO

night harness
worthy jungle
night harness
#

just in abit of a weird middleground where half the object works perfect for SO’s and the other half really really does not haha

latent latch
#

of course you do run in those corner cases which you do have to check, or add priorities

celest iron
latent latch
#

Eh, have you tested it in playmode without a button such that it renders after an amount of seconds?

gray mural
#

I want to implement a type for every ItemController and types that it can collide with.
So e.g. an enemy can collide with ground and wall

[Flags]
public enum ItemType
{
    Ground = 1,
    Wall = 2,
    Player = 4,
    Obstacle = 8
}

public ItemType itemType;
public ItemType collisions;

Do I have to make it as a Flags enum even though just 1 option in itemType has to be selected in the Inspector?
Or should it be smth else? I will then have to get ItemController's collisions and check if another ItemController can be placed on 1 square with it

latent latch
#

So, you don't want it as a flag enum because you don't want to multi select it in the editor, but you want it as a bitfield to do collision checking?

#

if that's the case you can probably change it via onvalidate

gray mural
#

I'm actually wondering if it's ok to use an enum in this case?

#

I haven't ever worked with flags enum before

#

is it comfortable to get multiple items from it? actually to enumerate though them

latent latch
#

the idea of a bitfield is figure out what's selected in one bitwise operation

#

opposed to iterating over the values

gray mural
#

I see, so & and | are commonly used with flags enums?

latent latch
#

right, im a little rusty with the stuff so I can't give the full details, but you're usually using them for when you need to know what you can/cannot collide with in a O(1) operation

gray mural
#
if ((myEnum & MyEnum.Smth) != 0)
#

this one?

latent latch
#

Yeah, that looks about right

gray mural
#

checking if myEnum contains MyEnum.Smth value I guess

#
if ((myEnum & MyEnum.Smth) == 0)
#

and this is "doesn't contain"

#

now I see, thank you, @latent latch

latent latch
quartz folio
#

You should start at 1 << 0

latent latch
#

isnt 1<<0 all none

jovial nymph
#

what could be the problem

gray mural
#

I think just 1, 2, 4 looks better

latent latch
#

It's just when you get into higher values

gray mural
tawny elkBOT
#
💡 IDE Configuration

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

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

VS Code*
JetBrains Rider
Other/None

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

gray mural
jovial nymph
gray mural
#

and please, don't crosspost

jovial nymph
#

my bad

gray mural
#

is this script a part of your project?

#

oh, lemme answer you, no it's not

#

it throws an error in weapon sway script

#

those scripts have to have 1 class that matches their names

#

so you have to name your class weapon sway

#

but it's impossible

#

that's why you have to google c# naming conventions

neon plank
#

How can I check if a VisualEffect has finalized running? With ParticleSystem I can do IsAlive(true), what is the equivalent?

latent latch
#

Haven't really tried those methods, but I remember someone mentioning them

neon plank
#

I tried with HasAnySystemAwake() but seems to always return true

spark flower
#
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/items.sav";
        FileStream stream = new FileStream(path, FileMode.Create);

        string[] _stash = new string[items.Length];
        int[] _amounts = new int[items.Length];

        for (int i = 0; i < items.Length; i++) {
            _stash[i] = items[i] == null ? "" : items[i].id;
            _amounts[i] = items[i] == null ? 0 : items[i].amount;
        }

        formatter.Serialize(stream, _stash);
        formatter.Serialize(stream, _amounts);

        stream.Close();

        Debug.Log($"Saved items data to file");
    }```
guys can i do something like this
neon plank
spark flower
#

basicly 2 separate variables in one stream?

neon plank
#

Or maybe the VisualEffects's graph is never sleeping? 🤔
I don't know how to use it, I'm just asked to execute some callback after it finalized.

latent latch
neon plank
#

ok

#

Thanks

fiery marsh
#

Bye unity

simple egret
# spark flower basicly 2 separate variables in one stream?

You could, but with this you need a way to deserialize. Unless items.Length always has the same value, you wouldn't know where the first array stops. So you have a few options

  1. Use another serializer, like JSON ones. BinaryFormatter has security vulnerabilities and should not be used after all.
  2. Write the array's length before the array itself, so you know how much to read and deserialize.
  3. Write to two different files (and optionally compress them to zip, easily doable with streams and the stuff in System.IO.Compression)
#

I mean point 2 wouldn't work anyway, I don't think BF will like not seeing the end of stream after it deserialized the first payload

spark flower
scarlet viper
#

How to convert that to a more safe version? I feel this wont always keep other axes properly

 lower.forward = (target - source).normalized;

And im rotating only one axis anyway.
Can i somehow rotate just one axis with a direction ?

limpid owl
#

any good HC framework ?

leaden ice
#

HC?

limpid owl
#

hyper casual

#

i've asked a question but got no answers last time

#

here

leaden ice
#

Sounds more like a monetization strategy than a style of game

#

ah ok tycoon park game is more descriptive

limpid owl
#

yeah

#

we have a proprietary solution for monetization

whole portal
#
public class MoveController : MonoBehaviour
{
    // ... (other variables)
    private Animator animator;

    void Update()
    {
        // Ground check
        if (characterController.isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        // Movement input
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        // Initialize animation booleans
        bool isStandingJumping = false; // New animation boolean

        // Check for movement
        if (x != 0 || z != 0)
        {
            // ... (handle walking, running, and moving jump)
        }
        else
        {
            // Handle Jumping while standing
            if (Input.GetButton("Jump") && characterController.isGrounded)
            {
                isStandingJumping = true;
                velocity.y = Mathf.Sqrt(jumpSpeed * -2f * gravity);
            }
        }

        // Apply gravity and move
        velocity.y += gravity * Time.deltaTime;
        characterController.Move(velocity * Time.deltaTime);

        // Set animation states
        animator.SetBool("isStandingJumping", isStandingJumping); // New animation state
        animator.SetBool("isIdling", !isStandingJumping); // Modified to consider new state
    }
}```
#

I have this issue with my code where the jumping animation won't fully play, if anyone can have a look and let me know why that is.

#

In the video I show the settings for my animator controller.

leaden ice
#

Also if you actually select the object with the animator you can watch the state machine in real time

whole portal
#

Thank you very much. So do I need to modify the code or do something in the animator ? I know some things are supposed to be controlled by the animator only. Ideally, I'd like the animation to work like this:

  • Spacebar needs to be held down, as soon as you release the spacebar (no matter how fast), the jump action / animation is canceled.
  • While spacebar is held, I would like a bit of delay before the character actually propels up, so that it appears that it takes momentum to jump (just like in real life, people don't instantly jump up, muscles need to contract first, body needs to prepare).
  • Then the character jumps up (ideally a variable which I can play with would be perfect, so that I can make sure the jumping action actually happens when the animation is ready for it).
  • If the player keeps the spacebar pressed, the animation would play in its entirety and then the character would come back to the ground, but will not jump again unless the spacebar key is released and held down again.

So I was wondering if I should set all this up in code (and how to do it or go about it) or if I should do something in the animator too.

@leaden ice

#

Also, your advice fixed the animation thank you, it's now function correctly but I'm wondering how to go about what I described next.

#

Basically exactly like this

#

I'll try to see if I can use a delay to achieve the same result.

modern creek
#

I have a mesh renderer with 2 materials on it. How do I remove one with Renderer.materials? I'm doing this, but it's leaving one on the renderer:

Renderer renderer = ...;
Material[] newMaterialArray = renderer.materials.Where(x => x.name != removeMaterial.name).ToArray();
renderer.materials = newMaterialArray;

Docs say something about destroying the material after?

#

or do the docs mean that I should be using SetMaterials() instead of materials = ...

#

oh, nevermind, SetMaterials doesn't appear until 2022.. i'm using 2021

minor pike
#

so i recently wrote a python script for installing a package. and it's very efficient too in terms of resource usage if i say so myself. but for some reason it also uninstalls the file right after. and the cycle happens like 500 times. any idea how to fix this?

import subprocess
import multiprocessing

def install_and_uninstall(install_exe, uninstall_exe):
    try:
        subprocess.run([install_exe], check=True)
        print("Installation successful!")
    except subprocess.CalledProcessError:
        print("Installation failed.")

    try:
        subprocess.run([uninstall_exe], check=True)
        print("Uninstallation successful!")
    except subprocess.CalledProcessError:
        print("Uninstallation failed.")

if __name__ == "__main__":
    install_exe = 'install.exe'
    uninstall_exe = 'unins000.exe'
    pool = multiprocessing.Pool()
    num_runs = 500
    results = [pool.apply_async(install_and_uninstall, (install_exe, uninstall_exe)) for _ in range(num_runs)]
    pool.close()
    pool.join()
dusk apex
minor pike
#

nah i'm at the right place i think. after all, it's a unity game

#

i didn't want to click on the installer myself, and wanted to do it with a python script

dusk apex
#

This isn't related to Unity, it's Editor or game development at all. Good luck.

minor pike
#

just imagine it to be related

#

¯_(ツ)_/¯

soft shard
# whole portal Thank you very much. So do I need to modify the code or do something in the anim...

I have not used them myself, though maybe you could try animation events: https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html - you could also look up tutorials on YouTube for better examples on how to use them and set them up

From your code above, it looks like your using the old Input class, so you could alternatively use GetButtonDown and store a variable of Time.time (https://docs.unity3d.com/ScriptReference/Time-time.html), and GetButtonUp to know when it is released to handle a "cancel" condition - you could then use that timed variable to know how long GetButton has been held for, and based on that, decide how long to delay executing your jump logic (which is similar to what an animation event could do for you as an alternative approach)

For handling jump itself, im not too familiar with the CharacterController (I often use a rigidbody + capsule collider for characters), though I imagine you could do something similar to a rigidbody approach, since gravity and jumping in most cases use the same y axis regardless of component: https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/ - and if you use GetButtonDown, then you have a chance in your code to know when a jump started, and can use that to prevent your last concern of instantly jumping while still holding the key down after a full jump has completed, you could even setup a bool and either unset that bool with a animation event on the last frame, or when "is grounded" becomes true again - and there may be other alternatives for your use-case, though these are first that come to mind, assuming I am understanding your scenario correctly

Learn how to jump in Unity, how to control jump height, plus how to jump without using physics, in my in-depth beginner's guide.

whole portal
dark kindle
#

would it be possible to store voxel rotation in 3 bits instead of 1 byte or more? for example 3 bits has a combination of 8 i think, which is more than 6 different sides.

#

left, right, up, down, front and back

dark kindle
#

Thank

unkempt sail
#

does anyone know how to map an array of objects based on indices recorded in another array

#

I am trying to serialize a deck of cards with a specific shuffle then reload said serialization

#

cards have a var called index for each card to know where it should be in the list

#

and I record these indices into a list, cardListIndices

#

I thought this would work but it doesn't```cs
for (var i = 0; i < Cards.Count; i++)
{
(Cards[cardListIndexes[i]], Cards[i]) = (Cards[i], Cards[cardListIndexes[i]]);

}``` ps. Cards is ordered according to their indices

somber nacelle
#

why not just .Sort using the index variable as the object being compared?

unkempt sail
#

let me try that

#

like this Cards = Cards.OrderBy(c => cardListIndexes[c.Index.Value]).ToList();?

somber nacelle
#

sure, or if Cards is a List then just use the Sort method

#

actually that wouldn't be correct anyway

#

if you were to use OrderBy it would just be Cards = Cards.OrderBy(c => c.Index.Value).ToList();

unkempt sail
#

well thats just sorting it from 0 to 52

#

aka an ordered deck of cards

somber nacelle
#

is that not what you wanted? you wanted to sort by the index contained in each card object, no?

unkempt sail
#

no, I want the card list to be sorted based on the indices of cardListIndexes

somber nacelle
#

and cardListIndexes serves what purpose?

#

because it sounds like you are way overcomplicating this

unkempt sail
#

well I want to keep the deck shuffled in the exact order

somber nacelle
#

okay so you store the index that the card should be at. is that not what you are doing?

#

why do you need to store an array of indices on each card?

unkempt sail
#

Look what I am actually trying to do is make a card game

#

It's online, so I need all the clients to have the exact same shuffle as the server shuffled them

somber nacelle
#

and that still doesn't answer why you need to store an array of indices on each card

unkempt sail
#

Because then I can map the card list based on their indices

#

If you have a better solution I am happy to hear it

somber nacelle
#

that still doesn't answer why you need an array of indices on each card. why not just store the card's current index directly on the card? then you use that like i showed you before

spring creek
#

Shuffle deck, give card current index... done. It will have the same order for each player

lean sail
#

from the description "var called index for each card" it sounds like they do store it... unless im misunderstanding

lean sail
#

and you have an array of indices to represent what should be the index, this part does not make sense

unkempt sail
#

each card has a the index where it was originally placed, like if you have bought a brand new deck, aka the order in which it was instantiated in

somber nacelle
#

they don't store the current index of the card on the card. they store the index they access it at in that other array. where that other array has the current index for some unknown reason

unkempt sail
#

Look honestly at this point I am lost to my own solution

somber nacelle
#

yeah that's pretty clear

lean sail
#

Yea i truly dont understand what Cards[cardListIndexes[i]] is supposed to do, so i assume you dont understand that part either

#

i mean syntatically i understand it, but logically doesnt make sense

unkempt sail
#

I have been trying to do this for like 3 hours now

lean sail
#

you might have an easier time doing this on a smaller sample (like 5 cards). at least then you can go step by step and see why your solution doesnt exactly make sense

unkempt sail
#

This is how I imagined aka sloppily wrote down how'd it would work

#

So I have a list of cards, (1, 7 , 10), indices are (1, 2, 3), I generate a list of random indices (3, 1, 2)

#

The card of the new shuffle is 10, I take the index of the current card (10), then slap it at the start of the card list

#

Then I guess I actually don't need to store where the card should be

lean sail
# unkempt sail So I have a list of cards, (1, 7 , 10), indices are (1, 2, 3), I generate a list...

did you run through how this example would actually work?
You have a random list of indices, you want these to be your new card order. Also lets just say its 0, 1, 2 and 2, 0, 1 cause index starts at 0
For loop happens:

i = 0, cardListIndex[i] = 2
Cards[2] = Cards[0]
Cards[0] = Cards[2]
You now have (10, 7, 1)

i = 1, cardListIndex[i] = 0
Cards[1] = Cards[0]
Cards[0] = Cards[1]
You now have (7, 10, 1)

i = 2, cardListIndex[i] = 1
Cards[2] = Cards[1]
Cards[1] = Cards[2]
You now have (7, 1, 10)

Does this align with what you want? Hopefully i didnt typo anywhere there, wrote this pretty quickly

unkempt sail
#

pretty much

lean sail
#

If that aligns with what you want, then whats wrong?

#

(7, 1, 10) also does not seem like the correct result for what it should be

unkempt sail
#

if the index list says (2,0,1) then the result should be (7,1,10)

lean sail
unkempt sail
#

Means that I need a goods night sleep

torn eagle
#

Anyone have any idea why the delayedObjects field isn't appearing in inspector?

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

public class DelayedStart : MonoBehaviour
{
    CheckLife lifeCheck;

    [SerializeField]
    public IDelayStart[] delayedObjects;

    [SerializeField] FishTips fish;

    private void Start()
    {
        lifeCheck = CheckLife.Instance;

        if (lifeCheck.initLoad)
        {
            StartCoroutine(fish.TypeText());
        }
        else { Destroy(fish.gameObject); }
    }

    private void Update()
    {
        if (fish == null)
        {
            Enable();
        }
    }

    void Enable()
    {
        foreach(IDelayStart starter in delayedObjects)
        {
            starter.DelayedStart();
        }
    }
}```
mellow sigil
#

Interfaces aren't serializable

torn eagle
#

That would make sense lol

#

What would be the easiest way to handle this then? Take in behaviours then cast?

latent latch
#

There's some plugins around but honestly I've kinda abandoned that idea

#

casting should be fine if you want to manage that, but replacing larger interfaces I think I've had to abstract a bit more

tame spruce
#

This doesn't really fall into any channel category, I'll try asking it here. On Windows, when you navigate a menu (such as the project folders/files window) with arrow keys, you can press CTRL + Right Arrow to recursively collapse and CTRL + Left Arrow to recursively uncollapse child folders. The same worked in the Inspector. If you did the same on a serialised List, all the child elements would get effected.

The same works when navigating folders on Mac OS, however, it doesn't work in the inspector. Anyone know a workaround for this? It is an immensely useful feature.

In the image I'm posting, if on windows if you did CTRL + Left Arrow, it recursively uncollapses "Levelable Upgrade Levels", Element 0 and Element 1.

#

And if you do CTRL + Right arrow, on Windows, it recursively collapses all the elements and child elements so everything is visible.

somber nacelle
#

this is a code channel, mate. #💻┃unity-talk for things that don't fit in any other channel

main shuttle
tame spruce
main shuttle
tame spruce
tame spruce
main shuttle
tame spruce
main shuttle
marsh wadi
#

I'm trying to put a breakpoint in UnityEngine.UI's EventSystem.cs; I've made unity generate the csproj files etc, I can see the source code, I can step through the source code, but breakpoints remain evasive

I've tried regenerating projects, removing .vs/obj/library folders and csproj files, building the project.. Any ideas?

main shuttle
# tame spruce Thank you very much!

Yeah it also doesn't work for me, sorry. I probably made a custom inspector for the list then, but that was years ago.
Doesn't seem to be default in Unity.

tame spruce
forest ravine
#

I'm so triggered right now, a professor of mine wholeheartedly defended the need for the existence of a Game Manager script in every project

#

It just violates any good principles of programming and making games that I know

hoary monolith
#

Hello I have this code right now used to fade in and out of a vignette post process but for some reason the second coroutine doesn't do the effect what could be the problem?

private void Awake()
{
    playerManager = FindObjectOfType<PlayerManager>();
    
}

private void Update()
{
    
    if (playerManager.isGloomHaunted)
    {
        StartCoroutine(gloomHauntingEffect());
    }
    else
    {
       StopAllCoroutines();
    }
}

IEnumerator gloomHauntingEffect()
{
    volume.profile.TryGet(out vignette);
    yield return startDuration(true, vignette, .5f);

    yield return new WaitForSeconds(1f);

    yield return startDuration(false, vignette, .5f);
    playerManager.isGloomHaunted = false;
}

IEnumerator startDuration(bool fadeIn, Vignette vignette,float fadeDuration)
{
    Debug.Log("Gloom Haunting");
    float minIntensity = 0f; // min intensity
    float maxIntensity = .4f; // max intensity

    float counter = 0f;

    //Set Values depending on if fadeIn or fadeOut
    float a, b;

    if (fadeIn)
    {
        a = minIntensity;
        b = maxIntensity;
    }
    else
    {
        a = maxIntensity;
        b = minIntensity;
    }

    float currentIntensity = vignette.intensity.value;
    Debug.Log(a);

    while (counter < fadeDuration)
    {
        counter += Time.deltaTime;

        vignette.intensity.value = Mathf.Lerp(a, b, counter / fadeDuration);

        yield return null;
       
forest ravine
#

Check if you have already a coroutine going on and if so, either cancel and restart or not start any more

orchid bane
#

Which data struct won't get a new entrance of the same value if I try to add it?

hoary monolith
#

the value of the intensity is what i meant

forest ravine
#

In between which lines?

hoary monolith
#

oh wait i see what you're talking about let me check

forest ravine
orchid bane
forest ravine
#

I like to make a Coroutine field and then check if it's not null and then set it to null at the end of the call

civic verge
#

hello
I have a camera script to move and rotate my camera (Im making a city building game)
The problem is when I rotate my camera and move it forward it doesn't go forward in the direction im rotated in
can anyone help?

forest ravine
orchid bane
#

Yep

forest ravine
#

Congratulations

#

You now will attain the power of

#

Hashset<T>

#

Good?

orchid bane
#

Yep! Thanks

forest ravine
#

Yay!

hoary monolith
forest ravine
#

Wow, I spotted it first try, how nice you were able to solve your problem

sharp acorn
#

What is CG.Alloc and why does it take like 60ms each time I instantiate something?

#

I changed some stuff since then but, it was working fine 10 minutes ago

main shuttle
loud wharf
#

In fact, i alr made one. :p

loud wharf
# loud wharf You can make a property attribute that restricts the input type to certain types...

The thing is tho, ur not actually serialising the interface, ur just restricting the input field to a type.
So gonna have to do this:
[Restrict(Restriction = typeof(IDelayStart))] public Monobehaviour[] delayObjects;
You'll have to cast it each time u use it.

Or more preferably... (For me)

public struct SerialisedIDelayStart {
  [Restrict(Restriction = typeof(IDelayStart)), SerializedField] private Monobehaviour[] _delayObjects;
  public IDelayStart DelayObj { get => (IDelayStart )_delayObjects; set => _delayObjects = (Monobehaviour)value; }
}

In this case, I basically just made a wrapper. So everytime i try to access it, it already casts it for me.

Here's the restrict attribute i made. :p
Just paste it in somewhere.

sharp acorn
#

I'm still drawing blanks as to what it could be, but that would at least help me narrow down the possible causes (once I find them xD)

#

Still, how does it take way more time to dispose of the memory than to allocate?

#

Or rather, why is it disposing of that much more memory

main shuttle
quartz vessel
#

Can anyone tell me how can i use dynamic string portion in button event function assigning

sharp acorn
#

Uff it's a bit spagetti but I'll try to illustrate you how the stack trace would look like

knotty sun
quartz vessel
solid mountain
#

I want to add bullets my player instantiates to a list so I can randomly access one if them and change a public value

#

How can I do that, add an instantiated object to a list

knotty sun
leaden ice
knotty sun
#

I was trying not to completely spoon feed

leaden ice
solid mountain
#

I forgot to set the list to new()

#

So it errored me

leaden ice
solid mountain
#

It seemed like it was skipping code

leaden ice
#

you would have gotten a NullReferenceException

#

which is an error

solid mountain
#

I'll check again and see if it works now

knotty sun
solid mountain
#

Then maybe I just didn't see the null reference. Thanks!

knotty sun
solid mountain
knotty sun
#

absolutely

#

It will save you hours and hours of unnecessary grief and aggravation

solid mountain
#

I hope it does lol

#

Because I already got some

knotty sun
orchid bane
#

My gun continuosly starts and stops firing when I don't even get the mouse button up, what do I do?

//called in update each frame
public void Shoot(Vector3 pos) {
        if(firing) UpdateTarget(pos);
        else
        {
            firing = true;
            StartFiring(pos);
            StartCoroutine(nameof(StopFiringCoroutine));
        }
    }

private IEnumerator StopFiringCoroutine() {
        while (firing)
        {
            firing = false;
            yield return new WaitForEndOfFrame();
        }
        StopFiring();
    }```
#

It's obvious to me that firing is continuosly switching between tru and false but idk what to do

dusk apex
#

You're immediately setting it back to false.

orchid bane
#

Oh, right

dusk apex
#

And next frame firing is likely set back to true
..
Repeat

orchid bane
#

Any ideas how to fix it?

dusk apex
#

What should it do?

#

I was just looking at the logic and not really at the question 😅

orchid bane
# dusk apex What should it do?

Shoot(Vec3) is called in update by player if fire button is pressed. I want the weapon to automatically turn off if there was no input this frame

dusk apex
#

What input system?

orchid bane
#

It works on events from input so the method isn't called if the button isn't pressed

dusk apex
#

So the new input system or some event based system right?

orchid bane
#

Yes

dusk apex
#

Alright thus why you're trying to handle stop procedurally

orchid bane
#

Yep

dusk apex
#

If the button was pressed, we'd set done to false and fire. At the end frame we set done to true. Next frame if done isn't set to true again ie shooting, we'll disable it.

orchid bane
# dusk apex ```cs done = false if firing Update Target else ...``````cs while firing...
public void Shoot(Vector3 pos) {
        fireRequested = true;
        if(firing) UpdateTarget(pos);
        else
        {
            firing = true;
            StartFiring(pos);
            StartCoroutine(nameof(StopFiringCoroutine));
        }
    }

private IEnumerator StopFiringCoroutine() {
        while (fireRequested)
        {
            fireRequested = false;
            yield return new WaitForEndOfFrame();
        }

        firing = false;
        StopFiring();
    }```
Works👍🏻
#

Tho stopping is now called every frame for some reason

dusk apex
#

Hmmm, stopping as in "StopFiring"?

orchid bane
#

Yes

dusk apex
#

That would only happen if fire requested was false and not set back to true

orchid bane
#

Put a debug log into the while loop, it's called the same count of times as the debug log in stop firing

dusk apex
#

Was shoot called every frame?

orchid bane
#

Let's check

dusk apex
#

I'm assuming the event system isn't skipping frames

#

Yeah, place a log there as well

#

You should see a pattern A B A B ...

orchid bane
#

Called each frame

dusk apex
#

Place a log before firing is set to false

#

So there ought to be a log in shoot, the while loop and below the while loop

orchid bane
#

Already placed, again, called each frame

orchid bane
dusk apex
#

What's the pattern? Are all three called?

orchid bane
#

Yep

#
private IEnumerator StopFiringCoroutine() {
        while (fireRequested)
        {
            print("falsing");
            fireRequested = false;
            yield return new WaitForEndOfFrame();
        }

        print("stopping");
        firing = false;
        StopFiring();
    }```
dusk apex
#

What does shoot look like?

orchid bane
#
public void Shoot(Vector3 pos) {
        fireRequested = true;
        print($"shoot request: {Time.time}");
        if(firing) UpdateTarget(pos);
        else
        {
            firing = true;
            StartFiring(pos);
            StartCoroutine(nameof(StopFiringCoroutine));
        }
    }```
#

Stopping happens on the same frame with starting

#

These are Time.time

dusk apex
orchid bane
#

To what

dusk apex
#

Since the routine starts immediately and gets to the yield.. at the end of this frame it'll continue again

#

False occurs and the while loop will break before the next frame

#

When you start a coroutine it occurs immediately

#

The yield only waits till the end of this frame

orchid bane
#

I don't understand

#

We are in Update

#

Why is it called immediately

dusk apex
#

That's how coroutines work.

#

Maybe a regular yield null before the while loop can skip a frame (the initial start of the coroutine)

#
yield return null;
while
    ...
    yield
...```
orchid bane
#

Does new WaitForEndOfFrame really happen before LateUpdate?

dusk apex
#

There's a wait for late update as well but that isn't the issue

#

The issue is that the coroutine occurs immediately up to the yield statement

orchid bane
#

It shouldn't

#

It should stop until LateUpdate

#

Idk how to fix it, for now moved it to LateUpdate and it works

dusk apex
#

When you start the coroutine it'll run up to the end of frame yield

orchid bane
#

Apparently WaitForEndOfFrame isn't waiting until LateUpdate

dusk apex
#

The end of this frame, do this

leaden ice
#

it's usually not what you want

#

usually you just want yield return null;

dusk apex
#

Just skip the first frame, everything else should be fine

orchid bane
#

Oh I understand

#

Or not

dusk apex
#
private IEnumerator StopFiringCoroutine() {
        yield return null;
        while (fireRequested)
        {
            print("falsing");
            fireRequested = false;
            yield return new WaitForEndOfFrame();
        }

        print("stopping");
        firing = false;
        StopFiring();
    }```
orchid bane
#

I understand, it sets firing to false and then runs again on the same frame

#

Thanks a lot guys! 👍🏻

fringe oyster
#

we are looking to hire unity game devs. Is there a help wanted channel here I am not seeing? Thank you

tawny elkBOT
fringe oyster
#

Perfect. Thank you!!!!

earnest gyro
#

SetActive(true) not working as intended

uneven slate
#

Hello. anyone know how to get the "add key" to show up on just general float values. in this case I can't just change it by some tiny amount to get it to pick it up as a keyframe. example of what I need (works on transform:)

#

vs what I see on a general script float:

heady iris
#

So it can be keyframed; it just doesn't give you the "Add Key" option?

uneven slate
#

Nope!

#

or, well, yeah. it can be keyframed, just no add key option.

#

do I need to put an attribute on the variable or script or something?

heady iris
#

hmm, I see that show up for float fields on one of my classes

#

specifically, on a float that's part of a struct field

#

how did you define "Main Rotor RPM"?

uneven slate
#

just a stock standard [serializefield]

    [SerializeField]
    public float MainRotorRPM = 395f;
heady iris
#

are you sure you're actually recording an animation?

#

I see this when I'm not previewing an animation, specifically

#

vs. when I am previewing an animation

uneven slate
#

I'm recording in the timeline window, hence why i can record the transform's values

heady iris
#

ah, maybe timeline behaves differently

wispy cave
#

how do i post a forum in unity forums

heady iris
#

doesn't it need an animator on whatever object you want to control things on?

#

i've barely used timeline

uneven slate
crude creek
#

Hello! I'm currently making a car game and I have a problem. I want to police cars spawn around the player, but I only want them to spawn in top of roads. Any ideas on how to do it? Thanks!

heady iris
#

how are your roads built?

#

are they a grid of models that snap together?

crude creek
#

yes

heady iris
#

if so, I'd just pick a random road and check if it's near the player

#

bonus points for randomizing the position on the road segment, but that's less trivial

#

since different road shapes will have different rules

#

that's where you might just slap down a few empties as valid car spawn points

spring creek
heady iris
#

so, each road piece would have a few GameObjects. pick a random object and put the car there.

crude creek
heady iris
#

Automating the problem is nice, but sometimes it's better to just hand-author a few spawn points and call it a day :p

#

If you have some kind of navigation system for the cars, you could probably take advantage of that

#

pick a random point and snap it into a legal position

crude creek
#

thanks!

dark kindle
whole portal
#

Can I get a bit of help with fixing these errors please ?

My chunk script uses Compute Shaders to update terrain chunks, but I'm running into errors that are a bit puzzling. It handles the creation and updating of terrain chunks. It uses Compute Shaders and Compute Buffers for terrain manipulation.

Exception caught: Value cannot be null.
Parameter name: buffer```
```vbnet
NullReferenceException: Object reference not set to an instance of an object.

What I've Tried:

  • Checked whether _trianglesBuffer is null before setting it.
  • Logged various variables to debug the state of the buffers and kernels.

I'd appreciate any guidance on how to resolve these errors. I'm leaving the link to my code in case it's needed here: https://pastecode.io/s/ng59uh9v

knotty sun
#

your code post is empty

whole portal
#

I apologise, I forgot to save. It is saved now, please refresh.

knotty sun
#

nope, still empty

spring creek
#

I see a single "S" but that probably isn't what you wanted to share?

naive swallow
whole portal
naive swallow
#

Hatebin does that sometimes

#

I don't really know why

naive swallow
knotty sun
#

I think it is the Debug.Log at line 184 throwing the NRE
But have a try catch around this line 173
MarchingShader.SetBuffer(kernel, "_Triangles", _trianglesBuffer);
but not around the same line at 186

#

the structure of the code makes very little sense

whole portal
#

Here's a bit more details in regards with the results form the logs, I'd post screenshots but the logs are too long. Uhm, if you guys want me to add additional debug lines let me know please. I'm trying to fix this since yesterday and can't wrap my head around it.

knotty sun
#

I have a feeling that _trianglesBuffer is not null but it is empty and that is causing
Debug.Log($"_trianglesBuffer count: {_trianglesBuffer.count}, size: {_trianglesBuffer.stride}");
to throw the NRE

whole portal
#

The code worked well before I realised I had to check for neighbouring chunks otherwise when digging between chunks this would happen. So I've tried to implement a dictionary and that functionality. I also have an issue where when I leave a chunk, if I dig on it, the digging information gets lost after I leave that chunk and come back. So these are the issues I am facing.

knotty sun
#

I really think you are going to need the debugger to crack this one

whole portal
# knotty sun I really think you are going to need the debugger to crack this one

Well somehow, after adding a few more debug logs in the construct mesh method I only get one error now. I'm once again showing the log in video as I do log a bit more on the buffer now and it's a bit more information, but I'll leave the error down bellow. The rest of the logs are showcased in the video.

The error:

UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at /Users/bokken/build/output/unity/unity/Runtime/Export/Scripting/BindingsHelpers.cs:48)
UnityEngine.ComputeBuffer.get_count () (at <915aecf868db4138bef6c93c90c19aea>:0)
Chunk.ConstructMesh () (at Assets/Scripts/Chunk.cs:171)
Chunk.UpdateMesh () (at Assets/Scripts/Chunk.cs:94)
Chunk.Create () (at Assets/Scripts/Chunk.cs:87)
Chunk.Start () (at Assets/Scripts/Chunk.cs:37)```
knotty sun
#

it tells you right here UnityEngine.ComputeBuffer.get_count ()

#

I was wondering if you were trying to pass in the wrong type of data

whole portal
#

I've added a breakpoint here and attached to unity.

knotty sun
#

you need to put the breakpoint on a debug inside the catch then look

whole portal
#

I think I've made a bit of progress in identifying the erorr wit ha small update on Release Buffers.

whole portal
knotty sun
#

It's obvious the trianglebuffer is null which is what is causing all the errors so you need to see why is it null?

whole portal
knotty sun
#

what you need to do is look at the stacktrace when trianglebuffer is null, then work backwards through the code to find out why

#

so breakpoint on the debug for == null

zinc parrot
#

hey if I have a cloth component on a skinned mesh, why is the bounds in the inspector correct, but the actual bounds displayed in gizmos are static/never change? how do I get the bounds displayed in the inspector in script? because skinnedmesh.bounds dont move with the cloth

#

interestingly if I turn OFF updatewhenoffscreen suddenly its all the correct bounds

#

but I cant do that, I NEED it to update when offscreen

#

heres what happens with it, with the wirebox being the current bounds as reported by SkinnedMeshRenderer.bounds(and also the bounds that unity normally draws over objects, meaning they both report the same)

#

oh unity 2021 btw

dawn nebula
#

Is there a c# collection that's like a list in that there's an expected order, but you can't have multiples of the same object?

#

Hashset has the second but obviously not the first.

whole portal
whole portal
#

First time doing a stack trace here 😄

modern creek
#

I'm wanting to make a Cinemachine setup with a VCam for every unit in the game and a VCam that is the "player override" camera (so a player can just drag-to-pan around the map if they're not following a specific unit).

I'm getting some wonky behaviour though if I just do vcam.position += (Vector3)offset where offset is the amount of "drag" that happened this frame. Do I need to configure a vcam somehow to just make it behave like a normal camera?

#

oooh wait I'm ... not converting world position from canvas position, nevermind.

modern creek
#

When using cinemachine, my vcam is reporting 0,0,0 for this on mouse down:

RectTransformUtility.ScreenPointToWorldPointInRectangle(Canvas.transform as RectTransform, eventData.position, Camera.main, out Vector3 position);

My understanding is Camera.main will still be correct when the vcam is active?

#

do i need to add vcams to.. something?

#

(debug on that line of code)

heady iris
#

what do you mean "reporting 0,0,0"?

modern creek
#

canvas looks right, camera.main is the main camera, click event position looks right.. and yet it's returning 0,0,0

heady iris
modern creek
#

the RectTransformUtility.ScreenPointToWorldPointInRectangle() puts 0,0,0 into the out position, yeah

heady iris
#

are you trying to get point on a screen space - overlay canvas?

rain minnow
heady iris
#

The cam parameter should be the camera associated with the screen point. For a RectTransform in a Canvas set to Screen Space - Overlay mode, the cam parameter should be null.

modern creek
heady iris
#

i'm unclear what it would even give you if you did that, since screen-space coordinates on an overlay canvas are just the world coordinates, iirc

#

(notice how an overlay canvas is HUGE in the scene view)

modern creek
#

Ah.. I didn't realize that

#

So I don't need to convert from screen-world for this?

heady iris
#

what are you trying to do?

modern creek
#

drag the camera around to pan (using cinemachine)

#

Lemme try without converting from screen to world

heady iris
#

so you've got a top-down camera and you want to be able to grab and drag the ground?

#

(to move the camera)

modern creek
#

yeah

#

I did it without the world-to-screen coordinates and it "works" but isn't scaling properly - ie, moving one pixel on screen sends the camera 100 pixels away

#

I thought I needed to convert the screen coordinate of the event click to world space

heady iris
#

i did that in an RTS by just looking at the screen-space delta, rotating it, and then applying that the position of the camera

#

i just eyeballed the movement rate

#

I originally raycasted to the ground, then made sure the camera moved so that the mouse stayed over that exact piece of ground

#

but it got very wonky at sharp angles

#
                    Vector2 delta = pointer - draggingLastPos;
                    delta *= 0.4f;
                    delta *= 0.5f + 0.5f * Mathf.InverseLerp(distanceMin, distanceMax, distance);


                    x -= delta.x * Mathf.Cos(pivotRad) - delta.y * Mathf.Sin(pivotRad);
                    z -= delta.x * Mathf.Sin(pivotRad) + delta.y * Mathf.Cos(pivotRad);
#

man that's some weird code

#

this was before I knew how to rotate a vector, lol

#

i think that'd just be Quaterion.AngleAxis(pivotRad * Mathf.Rad2Deg, Vector3.up) * delta

#

but you get the idea -- measure the screen space delta, rotate it to match the view direction, and move the camera

modern creek
#

this doesn't work either

heady iris
#

line 3 is there so that it goes faster when the camera is zoomed out

modern creek
#

(commented out line was my first attempt - getting the position in world space by converting from the utility method)

heady iris
#

well, you definitely can't just add the position directly

#

the screen position is X and Y

modern creek
#

it's adding the difference between the last frame..?

heady iris
#

isn't that gonna send your camera flying into space?

modern creek
#

it should match up to pixels moved, shouldn't it?

#

ie if I move the mouse 5 pixels to the left, setting the camera position 5 pixels to the left?

#

(in world space coords)

heady iris
#

if you move the mouse up, the Y will change

#

so you'll be raising the camera

modern creek
#

i'm in "Z" = towards/away

heady iris
#

ah, okay

modern creek
#

gotta grab kids i'll bbl in case you have any ideas 🙂

#

bbl

dawn nebula
#

Can Unity handle an online RTS with ~100 units?

night harness
#

sure

#

it can handle anything given the right context and standards

spring creek
dawn nebula
#

Right but I guess the better question is like

#

Does it have available tooling

#

To make the process

#

Not ass

#

Or will I need to go it on my own?

spring creek
#

What does "not ass" mean?
And tooling for which part specifically?
Probably no though, for the tooling

#

Gonna need your own pathfinding

#

Gonna need to make your own unit varieties of course

#

The NavMesh is much better now in unity though!

dawn nebula
#

Specifically the communication between host and client

#

For pathfinding I got A*

spring creek
#

I dunno about that side though, sorry

dawn nebula
#

Wasn’t there some new solution?

spring creek
#

NGO

dawn nebula
#

Something released within the last 2 years?

spring creek
#

Is the new one

dawn nebula
#

What’s it stand for?

spring creek
#

Netcode for GameObjects

dawn nebula
#

Ah yes that sounds familiar

spring creek
#

They also have Netcode for Entities for ECS

dawn nebula
#

Got any experience with it? Solid or nah?

spring creek
#

I do not have any, sorry

dawn nebula
#

Fair fair. I’ll give it a try.

spring creek
#

People seem to like it haha

lean sail
dawn nebula
#

Think Starcraft I guess.

lean sail
#

I guess then it matters more what you are syncing then and how often, should still be possible but I'd keep an eye on the network profiler occasionally

modern creek
#

I can't seem to get RectTransformUtility.ScreenPointToWorldPointInRectangle() working for the life of me. Code for a mouse down event:

public void OnDrag(PointerEventData eventData)
{
  RectTransformUtility.ScreenPointToWorldPointInRectangle(Canvas.transform as RectTransform, eventData.position, eventData.pressEventCamera, out Vector3 updatedPosition);
  Debug.Log($"Position: {updatedPosition}");
}

Gives me the following (when I drag around 0,0 in world space):

dusk apex
modern creek
#

It changes as expected.. it's just.. wrong.. 🤷‍♂️

#

(those values are near the origin in worldspace but they're clearly screen coordinates)

#

I'm using a vcam with cinemachine fwiw - but there's only one camera, and eventData.pressEventCamera is null (as expected) since i'm using screen overlay mode on the canvas

#

Unless I'm supposed to be using "Screen Space - Camera" as the render mode..

#

In which case it works but now I have another problem.. judder when trying to set the position of a cinemachine vcam

dusk apex
#

Looks like a hover event so perhaps try enter event data instead

modern creek
#

ooooooooooo

#

There's a typo in that blurb but I found the member.. enterEventCamera vs pressEventCamera, which now works for overlay mode canvas.. not sure why i'm getting judder though, but I suppose that's a cinemachine config thing that I can chase down. Thanks!

broken light
#

how do you instantiate gameobjects only to the prefab from editor code? when ever i instantiate on the target it spawns in the scene and not the prefab

quartz folio
broken light
#

let me check it

#

i dont see any mention of prefabs in the pin?

cosmic ermine
#

Creating a generic struct, and wondering if there is any "where T :" for numbers? As in uints, bytes, stuff that can be used as an index into an array.

somber nacelle
#

not until .net 7

cosmic ermine
somber nacelle
#

yeah, unity doesn't even have .net 5 support. when they finally swap to the core clr we'll get the latest version of .net but that's not expected until next year at the earliest and could potentially be an even longer wait

cosmic ermine
#

unfortunate, thanks for the info!

fast glade
#

Do custom editors literally not work in builds at all? I notice that whenever i run a build all the mechanics that rely mainly on custom editors just break. Ive done the #if Unity_engine but i didnt really think that it would completely nullify all the effects of the custom editor

somber nacelle
#

editor code doesn't exist in a build at all