#archived-code-general

1 messages · Page 142 of 1

heady iris
#

Linq is a good example of the usefulness.

#
List<int> nums = new() { 1, 2, 3, 4, 5 };
List<int> result = nums.Where(x => x < 3).Select(x => x * 2).ToList();
#

x => x < 3 is an anonymous function that returns true if its argument is less than 3

swift falcon
#

The fuck?

heady iris
#

x => x * 2 is an anonymous function that returns its argument times 2

#

This filters the list to numbers less than 3, then produces a new list whose values are doubled

swift falcon
#

What would take me an entire function in and of itself to do, bro does in 2 lines

heady iris
#

result contains 2 and 4

#

You could have make the functions non-anonymous, of course

#
public static bool LessThanThree(int x) {
  return x < 3;
}
#

obviously that's a bit of a nuisance

swift falcon
#

this must be how newton felt when apple fell on head

heady iris
#

You would then do nums.Where(SomeClass.LessThanThree) instead of nums.Where(x => x < 3)

#

Either way, you're saying "hey, use this function!"

#

This is ultra-common in functional programming.

heady iris
swift falcon
#

what I mean more is,

#

if given this problem

#

i’d have to do each operation separately

heady iris
#
players
  .Where(x => x.health > 0)
  .Where(x => x.faction == Faction.Dudes)
  .Where(x => x.florps == 10)
#

operation after operation

swift falcon
#

ok what the fuck does this even do lmao

heady iris
#

well, read each line

#

line 2: .Where(x => x.health > 0)

#

what do you think that produces?

swift falcon
#

is this even correct syntax

heady iris
#

yes, i've just split it across a few lines to make it less cluttered

swift falcon
#

oh i see

heady iris
#

you can reason about each line completely separately

swift falcon
#

what does => do

heady iris
#

In this case, it is used to define an anonymous function

#

notice how it has no name

heady iris
#

you access it as SomeClass.LessThanThree

#

x => x < 3 creates a function, but it's not named anything

#

it's just an object.

#

you can stuff it in a variable, of course

#

var lessThanThree = x => x < 3;

#

aka

#

System.Func<int, bool> lessThanThree = x => x < 3;

#

a function that takes an int and returns a bool

#

If you need to perform several statements, you add braces

#
System.Func<int, bool> lessThanThree = x => { Debug.Log("x is " + x); return x < 3; };
#

which is equivalent to

#
public static bool LessThanThree(int x) {
  Debug.Log("x is " + x);
  return x < 3;
}
#

Anonymous functions let you construct the function exactly when you need it. They can use local variables from the context they were created in.

#
Player admin = GetGameAdmin();
var nonAdmins = players.Where(x => x != admin);
swift falcon
#

christ i feel like a fucking idiot right now

#

i think this makes sense but i’d probably need to actually practice it

heady iris
swift falcon
#

(not sure how to do that since i don’t really get it that well)

late lion
#

No need to run before you can walk. Anonymous methods are not required to understand delegates. They're useful for when you do understand delegates.

heady iris
#

Indeed.

#
public static bool IsCool(Player player) {
  return player.name == "chemicalcrux";
}

public void Start() {
  foreach (var cool in players.Where(IsCool)) {
    Debug.Log(cool.name + " is cool");
  }
}
#

using names makes linq especially fluent looking

#

players.Where(IsOnFire)

swift falcon
#

me googling what Linq is

heady iris
#

It provides a bunch of methods for working with lists

#

(and any other thing that looks a bit like a list)

swift falcon
#

what is .Where

heady iris
#

well, before looking it up

#

can you guess what a function called "Where" does?

#

a function that takes a list

#

and returns a new list

swift falcon
heady iris
#

"give me a new list where the items match this rule"

swift falcon
#

yeah ngl would not have guessed that

heady iris
#

i do think "Filter" would be better

swift falcon
#

i would have presumed it returned where anything that met that condition was in the list

heady iris
#

LINQ uses a lot of terminology from databases

heady iris
#

oh

#

well, not the indices :p

#

yeah

#

i misread.

swift falcon
#

you’re chemicalcrux not misread

heady iris
#

Except is a nice one

#
List<int> numbers = new() { 1, 2, 3, 4, 5 };
List<int> evens = new() { 2, 4, 6, 8, 10 };
List<int> result = numbers.Except(evens).ToList();
#

what do you suppose the result will be?

swift falcon
#

and doing so in such a short space

#

Got Dam

heady iris
swift falcon
#

sorry iterating

heady iris
#

It results in very terse code

#

I think it's also the most obvious way to demonstrate how to use delegates

#

The other straightforward example are events

#

where you say "hey, call this method when something happens"

swift falcon
#

is there anywhere i can practice using delegates?

mossy shard
#

best way to handle knockback is to add an impulse to the target in the forward direction of the player when i am hitting?

heady iris
#

which might just be the forward direction of the player

mossy shard
#

ye what i said

#

but when i tested it feels like a force push from star wars

#

even when adding momentum and such

heady iris
#

then the enemy doesn't have much drag

mossy shard
#

A you're right

#

i should add more drag when doing it, thanks for the suggestion

heady iris
#

For example, if you use the new input system, you'll use them a lot

#
InputActionReference jumpAction;

void OnEnable() {
  jumpAction.action.performed += Jump;
}

void OnDisable() {
  jumpAction.action.performed -= Jump;
}
#

performed is an event. You can subscribe to it by adding your method to it. You can unsubscribe by removing the method.

#

your Jump method gets called whenever the player hits the jump button

swift falcon
#

sorry again if wrong channel, but the hell is this now?

#

ill try running unity as administrator

heady iris
#

well, it says your scripts had compiler errors

swift falcon
#

i am 100% sure the error isnt in my code, it also goes to playmode successfully

thin aurora
#

Does the error persist after you clear your console and trying to do something?

swift falcon
#

dont know right now

#

im trying to open it back

#

because every time i close it, it hangs in task manager, if i kill it it says "cant kill an exiting process" or "access denied" and also "project is already open"

heady iris
#

smells like a "delete library and let it reimport" situation

swift falcon
#

its currently at this "c library stage" and it errors mostly here, lets see

#

anyone knows what its now?

gray mural
wide fiber
#
public class P_Input : MonoBehaviour
{
    Vector3 moveInput;
    Vector3 rotateInput;
    public float rotationAxisX;
    public float rotationAxisZ;
    public float xAxis, zAxis;

    private void OnEnable()
    {
        InputSystem.EnableDevice(Gamepad.current);
    }

    private void OnDisable()
    {
        InputSystem.DisableDevice(Gamepad.current);
    }
    private void Update()
    {
        HandleInput();
        RotateInput();
    }
    void HandleInput()
    {
        xAxis = moveInput.x;
        zAxis = moveInput.z;
    }

    void RotateInput()
    {
        rotationAxisX = rotateInput.x;
        rotationAxisZ = rotateInput.z;
    }
    private void OnMove(InputValue value) => moveInput = value.Get<Vector3>();
    private void OnRotate(InputValue value) => rotateInput = value.Get<Vector3>();
}```

Hi sorry, my rotation works thru right analog stick. But the thing is, it works only if i push the stick from left to right vice versa and diagonaly too but it wont rotate if i push directly up or down. It need it to do that so i can make my character rotate kinda smoothly based on where i push my stick?
wide fiber
# stable osprey switch z to y

Sorry no, it works weird. because my game is like topdown, when i switch to y, it doesnt rotate like how it should. it rotates by flipping around.

stable osprey
#

well, still, there's no inputVector.z afaik

#

also, when do you call OnMove and OnRotate? I don't see that in the code

#

and on top of that, are you sure you handle rotation correctly? I can't tell from this code either

#

but for starters I think your stick doesn't work at all on the Y (vertical) axis because you're not using it

#

@wide fiber This should be enough to handle the input:

public class P_Input : MonoBehaviour
{
    public Vector3 moveInput;
    public Vector3 rotateInput;

    private void OnEnable()  => InputSystem.EnableDevice(Gamepad.current);
    private void OnDisable() => InputSystem.DisableDevice(Gamepad.current);
    private void OnMove(InputValue value)   { var input = value.Get<Vector3>(); moveInput = new Vector3(input.x, 0, input.y); }
    private void OnRotate(InputValue value) { var input = value.Get<Vector3>(); rotateInput = new Vector3(input.x, 0, input.y); }
}

or if you have your extensions set up:

    private void OnMove(InputValue value)   => moveInput   = value.Get<Vector2>().XZ();
    private void OnRotate(InputValue value) => rotateInput = value.Get<Vector2>().XZ();
wide fiber
stable osprey
#

np!

gray mural
#

how to make breakpoint work on line 112 just when it throws error?

#

is it even possible?

unkempt knoll
#

Does someone know why this doesn`t work? Doesnt give an error, does nothing.

using UnityEngine;

public class Movement : MonoBehaviour
{
    private CharacterController controller;
    public float standingSpeed = 20f;
    Vector3 velocity;
    public float gravity = -10f;
    public float jumpHeight = 4f;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Set speed based on the character's state
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 direction = transform.right * x + transform.forward * z;
        controller.Move(direction * standingSpeed * Time.deltaTime);

        // Gravity and jumping code...
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
        
        if (velocity.y < 0 && controller.isGrounded)
        {
            velocity.y = -2f;
        }

        if (Input.GetButtonDown("Jump") && controller.isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }
    }
}
swift falcon
#

hello, I am trying to figure out how why this internal Unity process is taking so much time to execute, and I am hoping someone can point me to where to look:

the DeformationManager.LateUpdate function is taking at least 100ms per frame in the profiler. anyone can help me understand why and how to improve it? thanks

late lion
swift falcon
late lion
swift falcon
late lion
#

How many do you have?

swift falcon
late lion
#

Ok, then I think that amount of time is expected.

#

You could try using the GPU skinning option if you're using URP.

swift falcon
late lion
#

I don't know where it's configured, I just know it's available in version 10+

swift falcon
late lion
#

And the client would only update ones visible to it.

desert wind
#

For my teleporting script, I made it so when the player is pressing E AND touching a door tagged "SafeZoneDoor" they get teleported to an empty tagged "SafeZoneCenterEmpty", or at least that's what is supposed to happen. for reasons I do not understand it gets teleported across the map instead.
https://paste.ofcode.org/EMXLQ2ZZ5de5iQ2s48dhZH
The player should be getting teleported to the transform.position of the empty gameobject

swift falcon
# late lion I doubt the server needs to update mesh skinning. You should look into disabling...

yeah that makes sense. when i'm playing as host, i'll need to have it enabled probably. but need to figure out how to only update ones visible to it. should be handled by my Spatial Hashing Interest Management

also, the game runs perfectly fine outside of the editor as separate Client and Server, this is only in Host mode that i experience all this latency and it's tough to test.

shut cargo
#

Hi, i have a question about DOTween. When i use DoFade(0f, 1f) on an image it works fine, the image fades away completely. But when i use i.e. DoFade(100f, 1f) it does nothing, but it should be reduced by about a third, right? Alpha is between 0 and 255.

#

*reduced by about 2/3

late lion
shut cargo
spark kiln
#

In my 3d game of couch party type, I have 2 characters, one of which is wasd and the other is guided by an arrow. I want to tie these two characters together with the help of a chain or rope and just want them to go around together. Is there a resource or method that can help me do this?

shut cargo
unkempt knoll
#

Does someone know why this doesn`t work? Doesnt give an error, does nothing.



using UnityEngine;

public class Movement : MonoBehaviour
{
    private CharacterController controller;
    public float standingSpeed = 20f;
    Vector3 velocity;
    public float gravity = -10f;
    public float jumpHeight = 4f;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Set speed based on the character's state
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 direction = transform.right * x + transform.forward * z;
        controller.Move(direction * standingSpeed * Time.deltaTime);

        // Gravity and jumping code...
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
        
        if (velocity.y < 0 && controller.isGrounded)
        {
            velocity.y = -2f;
        }

        if (Input.GetButtonDown("Jump") && controller.isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }
    }
}```
swift falcon
#

<3

soft shard
# unkempt knoll Does someone know why this doesn`t work? Doesnt give an error, does nothing. ```...

Depending on what "it doesnt work" means, I assume you mean it doesnt move when you give it horizonal/vertical input, and I assume the script is attached to a relevant object with all your values assigned correctly, I would start with debugging it - comment out all your gravity/jump logic, output what your "x" and "z" values and "direction" is, and maybe output the math your using inside Move, to make sure your getting the values your expecting, if it moves then, likely your gravity logic is affecting it, if it doesnt, likely your calculations may be wrong

unique sparrow
#

I am currently working on a gun script for a top down shooter game, but when in AR mode it instantiates too many bullets at once and I can't seem to figure out what is going wrong in the script.

gray mural
#

but I cannot say more without further context

unique sparrow
#

Here I will send the script

#

I am just getting the file now

gray mural
#

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

unique sparrow
gray mural
#

what is that?

unique sparrow
#

How am I supposed to put the text in the discord chat

#

I am trying the links now

#

but it is not a long script

gray mural
unique sparrow
#

alright thanks

gray mural
unique sparrow
#

What do you mean?

gray mural
#

also you should not compare bools

#
bool isPistol = true;

if (isPistol) // works
if (isPistol == true) // works too
unique sparrow
#

ok I will change it

gray mural
unique sparrow
#

What

gray mural
unique sparrow
#

The bullets are spawned in ShootMechanicAR()

gray mural
#

but yeah, just when button is pressed

#
private void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        if (isPistol) ShootMechanicPistol();

        else if (isAR) canShoot = true;

        else if (isSniper) canShoot = false;
    }
    else if (Input.GetButtonUp("Fire1") && isAR == true) canShoot = false;

    if (canShoot) StartCoroutine(ShootMechanicAR());
}
#

your script ordering is quite strange

#

but yeah, I think it's quite logic that canShoot is true quite often

#

just print when coroutine starts

unique sparrow
#

ok I will try it out thanks

#

Ok so the shoot function is being called when the button is pressed but the same problem is occuring and it is that when the function is being called it spawns too many bullets at a time. I took the code block that you send and replaced my whole update function with it.

gray mural
#

I have already that that canShoot is true too often

#

you already know your issue, try to solve it now

#

it shouldn't be that difficult

#

but wait, anyway.

#

it's just called when button is pressed

#

that shouldn't spawn to many bullets

unique sparrow
#

I can show you a video of what is happening if you want

gray mural
#

but what do you even do this?

yield return new WaitForSeconds(0.5f);
#

it's at the end of your method

unique sparrow
#

Yeah I was just trying that out to delay it everytime the function was called

#

I probably just left it in by accident

gray mural
#

you probably gonna use yield return null; or yield break;

unique sparrow
gray mural
unique sparrow
#

Yeah I will use that one as a minigun weapon

#

But I am just trying to make a simple AR now

#

You unlock the guns using points you get from killing zombies

#

AR will be cheaper than minigun

rain minnow
gray mural
#

@unique sparrow print what method is called

#

and ShootMechanicAR() should have void type too

unique sparrow
#

like print it when it is called in the debug log?

#

'''void IEnumerator ShootMechanicAR()'''

rain minnow
gray mural
#

void ShootMechanicAR() { ... }

unique sparrow
#

so then I get rid of the coroutine?

gray mural
gray mural
unique sparrow
#

So no IEnumerator and I just get rid of the coroutine entirely?

rain minnow
#

Keep in mind Print only works with scripts derived from MonoBehaviour. It won't work on regular classes or SOs. Debug.Log works for everything though . . .

gray mural
#

also they gonna see it when they get error

modern grotto
#

What's a good way to implement status effects in my game?
I have a character that runs around and shoots multiple projectile types, and I want each type of projectile to apply a unique status effect to the enemies it hits (slow, stun, bleed, etc) and I also want to include other status effects like immunity.
What's a good approach to do this?

gray mural
#

it should be void, because you don't need to yield return anything

unique sparrow
#

this is what the code looks like now

prisma birch
#

I just upgraded versions from 2021LTS to 2022LTS and am getting a bunch of warnings related to VFX Graphs and the generated compute shaders. Anyone know how to fix these? I tried resaving/recompiling the graphs but no dice.

gray mural
unique sparrow
#

very last line

#

of ShootMechanicAR

surreal blaze
#

Hey something to bother

I been trying to follow a guide on making attack combo animations
But from what i have done im having an issue where my statemanger isnt swapping states so i cant get the animations to play at all
Im not so sure why its not swapping so i was looking to maybe get some help

gray mural
unique sparrow
#

835 times so I believe every frame

gray mural
unique sparrow
#

So how would I go about slowing it down so it is called not every frame but maybe once per second

#

well faster than one second

gray mural
#

here

#
else if (isAR) canShoot = true;
#

you should call that method here

#
else if (isAR) ShootMechanicAR();
#

that's because you assign canShoot to true when button is pressed

#

and assign it to false when it is released

#

bullets are spawned within time you still hold that button

unique sparrow
#

that part works fine

#

I just want to slow down the instantiation

gray mural
#

it was really stupid of me not to mention it

gray mural
#

I have already said you your issue

#

fix it

#

if you need it

#

you can slow down the instantiation by adding offset, but first fix this

unique sparrow
#

so I move '''cs else if (isAR) canShoot = true;''' right above else if (isAR) ShootMechanicAR();?

gray mural
#

don't use canShoot

#

just use that coroutine when you need it

#

and ping me, please

unique sparrow
gray mural
#

and you remove canShoot permanently

unique sparrow
#

And I do a coroutine instead?

unkempt knoll
# soft shard Depending on what "it doesnt work" means, I assume you mean it doesnt move when ...

oh, sorry, no. I meant different code haha, sent the wrong thing. I wanted to send this:

using UnityEngine;

public class OpenDoorATM : MonoBehaviour
{
    public float interactionRange = 3f;
    public KeyCode interactKey = KeyCode.E;

    private bool isInRange = false;

    private void Update()
    {
   
        if (isInRange && Input.GetKeyDown(interactKey))
        {
            PerformInteraction();
        }
    }

    private void OnTriggerEnter(Collider other)
    {
       

        if (other.CompareTag("Player"))
        {
            isInRange = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        
        if (other.CompareTag("Player"))
        {
            isInRange = false;
        }
    }

    private void PerformInteraction()
    {
        
        Debug.Log("Interaction called!");
    }
}





gray mural
#

you call method instead

gray mural
gray mural
edgy sage
#

Hi! This might be a stupid question but I'm trying to figure out why my ScriptableObject state is persisted on Unity Editor but on Android it seems to reset on each application run. For example property amountAvailable is reduced to 0 during runtime and properly persisted on the editor but is reset back to 1 on Android on each run.

Any ideas what I might be missing here? Below is simplified item class in question:

    [Serializable]
    public class Item : ScriptableObject
    {
        public ItemType itemType;
        public int amount = 1;
        public string itemName;
        public string description;
        public int maxAmountAvailable = 1;
        public int amountAvailable = 1;
    }
unique sparrow
gray mural
unique sparrow
#

I am tryint

#

trying to I am not completely sure what you mean

#

So I get rid of canShoot

knotty sun
gray mural
unique sparrow
#

and run a coroutine instead?

gray mural
#

please, read my previous messages

rain minnow
gray mural
unique sparrow
rain minnow
gray mural
unique sparrow
gray mural
#

they just have too many bullets spawned

rain minnow
#

they still need a fireRate to only spawn the bullet based on the rate of fire . . .

rain minnow
#

that's what i was originally suggesting . . .

gray mural
#

they just need to do a coroutine

#

it's the best way that I see

rain minnow
#

but that is the solution to their issue . . .

gray mural
unique sparrow
#

So how do I put in the fire rate because it was working fine with the canShoot and all I needed was the firerate

gray mural
#
private bool canShoot = true;

private IEnumerator Shoot()
{
    canShoot = false;

    // some stuff here

    yield return new WaitForSeconds(2f); // do a variable from it

    canShoot = true;
}
#

and then just check if canShoot

#

quite easy

rain minnow
gray mural
#

delay between shooting

rain minnow
#

exactly, that's the fireRate my dude . . .

#

the rate of fire at which the gun shoots . . .

gray mural
#

my English is bad anyway

unique sparrow
gray mural
#

you have understood the logic

gray mural
#

and you were not using it correctly

#

now you add it one more time

#

and yeah, now it's Coroutine

unique sparrow
#

Can you put it in the code with the rest of the script so I can see where exactly I am supposed to put everything because I am still confused

gray mural
#

I don't see why can't you do it yourself

unique sparrow
#

Because now it is saying on the editor that not all code paths return a value\

gray mural
#

probably you return just in bracket or don't return at all

unique sparrow
#

I still dont get it can you send what the update function should look like

spark kiln
#

In my 3d game of couch party type, I have 2 characters, one of which is wasd and the other is guided by an arrow. I want to tie these two characters together with the help of a chain or rope and just want them to go around together. Is there a resource or method that can help me do this?

gray mural
# unique sparrow I still dont get it can you send what the update function should look like

I give up, you cannot even copypaste what I have sent you
Just call this Coroutine in Update, that isn't that hard, is it?

private void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        if (isAR && canShoot) StartCoroutine(ShootMechanicAR());
    }
}
private IEnumerator ShootMechanicAR()
{
    canShoot = false;

    // some stuff here

    yield return new WaitForSeconds(2f); // do a variable from it

    canShoot = true;
}
wary coyote
#

I am trying to code a spline follower but I am spending hours and getting nowhere stumped. I know verbally exactly how I want it to work but I can't figure out where the problems that are @#$@^ing it up are occuring.


    void Update()
    {
        if (animate)
        {
            UpdateTimeValues();
            MoveTransformsOnSpline(spline, spacing, techTree, loop);
        }
    }

    private void UpdateTimeValues()
    {
        for (int i = 0; i < techTree.Length; i++)
        {
            float velocity = (speedOverTime.Evaluate(techTree[i].time));
            techTree[i].time += Time.deltaTime * speed * velocity;
        }
    }

    public void MoveTransformsOnSpline(SplineContainer spline, float distance, SplineFollower[] followers, bool isLooping)
    {
        for (int i = 0; i < followers.Length; i++)
        {
            float t = followers[i].time; // Calculate position of each transform

            // Check if t is out of bounds
            if (t > 1 && isLooping)
            {
                t = 1 - t;
            }
            else if (t > 1 && !isLooping)
            {
                t = 1;
                animate = false;
            }
            Vector3 position = spline.EvaluatePosition(t);
            followers[i].transform.position = position;
            followers[i].time = t;
        }
    }
}```









#

What SHOULD be happening is every array object moves along the spline at their own speeds and positions, but relative to eachother via their initial spacing

#

but what IS happening is it just completely @#$@6s up in new amazing ways every time I run it, sometimes they go backwards, sometimes they loop only once

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.

wary coyote
#

I didnt think it looked like too much code, thats not a large block to me it fits all in one screen

jaunty needle
#
using System.Collections.Generic;
using UnityEngine;

public class MessagesManager : MonoBehaviour
{
    
}
[System.Serializable]
public struct TextMessage
{
    public enum Senders { Dad, Wife, Son }
    public string textMessage;
}

How do I have this enum be accessible from both the class and the struct?

rain minnow
jaunty needle
#

Just a script dedicated to the enum?

rain minnow
#

the enum which you speak of . . .

knotty sun
jaunty needle
#

Aight cool

#

oh damn you can just do that

rain minnow
#

as long as it's outside of the class or struct its separate and not a child of that class or struct . . .

jaunty needle
#

Hey again, when I set the constraint for the width, when I do preferred size, it chooses its own size

#

Unconstrained

#

Preferred size

lean sail
#

Width meaning horizontal

jaunty needle
#

It does this

#

Acc it's working pretty well here

#

My thing is

#

I wanna increase the height of the sprite

#

from below only

lean sail
jaunty needle
#

It's in world space

lean sail
#

It has a rect transform

jaunty needle
#

When I try to use the rect tool it doesn't give me the options

rain junco
#

i have a problem rn and it doesnt let itself fixed and i already changed to private and public again nothing works

jaunty needle
#

ah, it's rect transform is... bugged out

#

Cuz it has a width of 1 and a height of 0

#

Oh I fixed it, I removed the rect transform

jaunty needle
#

How can I modify this value? As in stretching it from below

compact spire
#

Is there some sort of assembly seperation between classes under Assets\Scripts\Editor and Assets\SomeOtherFolder ? I can't seem to use any the namespaces in the editor folder in the other directories.

somber nacelle
#

correct, the Editor folder gets included in the Editor assembly. you should not be using the editor assembly in non-editor code either

leaden ice
#

Editor is a special folder. All scripts in ...what box said^

compact spire
#

Phew, I was able to get around the issue by moving a class outside of Editor that is referenced by a scriptableObject

#

I've been trying to have a class picker in my scriptable objects

#

it finally works

#

2 days of work to avoid having to make and update a switch statement

west path
#

i am using a Parallel Job to try and make noise for a sphere and it is coming back warped. i believe this is because of my x,y,z values and how i got them. i was just wonder if anyone knows the corect way to get these values or if I did code this rights the job is just messed up because it is a Parallel job. i had it as a normal job and was working fine just slower

var x = index % Diameter;
var y = (index / Diameter) % Diameter;
var z = index / (Diameter * Diameter);
jaunty needle
#

I have this script that spawns textmessages and resizes them automatically, but if the box is too big it starts to overlap, I tried to fix it using this line of code but it didn't work

#

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

jaunty needle
#
    void SpawnTextMessages()
    {
        for(int i = 0; i <  textMessages.Length; i++)
        {
            Vector2 spawnPos = new Vector2(messageYPosition.localPosition.x, messageYPosition.localPosition.y + spaceBetweenMessages * i);
            GameObject spawnedTextMessage = Instantiate(messagePrefab, spawnPos, Quaternion.identity, messagesParent);
            


            TextMeshProUGUI text = spawnedTextMessage.GetComponentInChildren<TextMeshProUGUI>();
            text.text = textMessages[i].textMessage;

            SpriteRenderer spriteRenderer = spawnedTextMessage.GetComponentInChildren<SpriteRenderer>();
            spriteRenderer.color = GetColourFromEnum(textMessages[i].sender);
            Transform spriteTransfrom = spriteRenderer.transform;

            float preferredHeight = text.preferredHeight;
            int numberOfLines = Mathf.RoundToInt(preferredHeight / preferredHeightInterval);

            spriteTransfrom.localPosition = new Vector2(spriteTransfrom.localPosition.x, spriteTransfrom.localPosition.y + (positionToSizeYRatio.x * numberOfLines));
            spriteTransfrom.localScale = new Vector2(spriteTransfrom.localScale.x, spriteTransfrom.localScale.y + (positionToSizeYRatio.y * numberOfLines));

            float halfHeight = spriteRenderer.transform.localScale.y / 2f;
            spawnedTextMessage.transform.localPosition = new Vector2(spawnedTextMessage.transform.position.x, spawnedTextMessage.transform.position.y - halfHeight);
        }
    
    }
peak wing
#

how to set cursor to the center of screen(i have lockmode locked)?

swift comet
#

I dont come from C#, using async a lot recently. I came into a lot of places where I have a private async Task<T> MethodA() that contains a call to private void MethodB() and I dont really need MethodB to be async but I need to call it from the async method because thats just how the chain of calls came down to be.
Am i doing it wrong or is that okay? Mostly asking due to the annoying warning CS1998, last option would be to supress it project wide unless I can solve it without suppresion.

#
private async Task<T> MethodA()
{
  await SomeTask; //etc
  MethodB() //no await, synchronous method call.
}

private void MethodB(){...}

simple egret
#

If you don't plan on awaiting anything in the method, then you can remove the async modifier, and just return a completed Task directly with return Task.FromResult(yourValueToReturn)

swift comet
#

Is that a good practise (not that im doubting the answer) just wondering if its faster to return as is, or return a task? I guess creating a task creates some overhead.

#

But i imagine it is nothing.

simple egret
#

Only return a Task if the caller is meant to be async and await it itself. Else the whole method chain can be non-async

#

What async does in reality is transform your method into a big state machine, that allows the code that's awaiting it to follow the progress of the task (running, completed, faulted). That's why you technically don't need any return on an async method that returns Task, it's all handled by the compiler for you.

#

With synchronous methods that still return Task or Task<T>, no state machine! You have to return a task yourself, and that's what Task.CompletedTask or Task.FromResult() does, gives you a task that's already completed

swift comet
#

Ah thanks, I somewhat knew about the state machine but not the second part. Thanks, ill give it a shot. I usually dont want to suppress warnings unless really needed 😅

river kelp
#

Hey, I am trying to make sprites flash white in certain situations, and currently I'm looking at doing it through a shader/material. The tutorial I found does this:

#

if I'm not mistaken, that creates a whole bunch of new materials, does it not?

#

Essentially every single object with this will get its own material?

lean sail
river kelp
#

But doing this sprite flashing thing seems so common

#

there has to be a common pattern for this, right? It's in every game basically

lean sail
#

a common pattern for what?

river kelp
#

sprites flashing white

#

on damage, etc

lean sail
#

does the tutorial u are following not work or something? im confused on what the issue is even

river kelp
#

Every material is a bunch of overhead

#

Ideally you would have just a few

lean sail
#

u can destroy them after they are finished being used, but u need to actually have them allocated somewhere so u arent just editing the actual material asset..

#

calling this overhead is like calling an int inside a class overhead

river kelp
#

N..nah.. Every material is an entirely separate drawcall

lean sail
river kelp
#

It's one thing to have like, 10 materials or whatever rendering different things in the game. Another thing entirely to have 3-5 materials per enemy in the game

#

Materials are like, one of the easiest ways to mess up your performance, so I would think there was a reasonable way to avoid making more..

lean sail
#

Unless you want to use a different set of sprites instead, i dont see what alternative you think there can be

river kelp
#

Well, material property blocks are one right

lean sail
#

also

Use it in situations where you want to draw multiple objects with the same material, but slightly different properties

river kelp
#

Right, so property blocks also break the batcher

river kelp
#

like a variable "white" amount that I can set

#

Anyway, the difference is pretty extreme so ideally I'd want to avoid too many

lean sail
#

I dont see how thats related to your case of wanting to edit a material at runtime

river kelp
#

editing the material creates a new instance of it, right?

#

Which means every object that wants to edit its materials

#

has different materials

lean sail
river kelp
#

Yeah and editing materials during runtime increases the amount of materials in the game

#

which is bad, because every material has a huge amount of overhead

#

enough that 4 materials lowered that guys fps from 50 to 14

lean sail
#

have u noticed an actual performance issue yet or are just speculating

#

yea 4 materials... on a grid of houses...

river kelp
#

Of course it depends on the amount that's used and how many objects are in the game right

lean sail
#

Yes that applies to literally anything

#

profile, then worry about this if u notice an issue

river kelp
#

It would just look like rendering takes a lot of time

lean sail
#

It would also look you are thinking about this in your head and have not profiled

river kelp
#

It's the same as getting the transform basically

#

you don't notice it until it creeps up on you

#

and when you profile, it just looks like you've reached the max your computer is capable of

#

I know optimizing early is bad, but if you riddle your game with really slow calls there's no saving it afterwards

#

each of them will show up as 0.02% on your profiler

lean sail
#

theres a difference between writing clean code that you feel is sufficient for the task, and pre optimizing

#

no one out here intentionally writes slow code knowing theres a better solution, you only look if theres a better solution if you notice an issue

river kelp
#

I mean that goes directly against my transform get example

#

we all do it without caching it

#

we know it's slow

#

you will never notice it being an issue

lean sail
#

i honestly dont know what you mean with the transform example

river kelp
#

getting the transform, like

#

"myObject.transform"

#

is extremely slow

lean sail
#

who says thats what everyone does?

river kelp
#

Most code I've seen does it

lean sail
#

barely anyone actually stores references to game objects. U only need it if u need to use .SetActive

river kelp
#

no, I don't mean another game object

#

if you want to get your own position, what do you do?

#

to the object you are in?

swift comet
#

Im pretty sure its not slow as its cached

river kelp
#

'tis not, unfortunately

#

unless they changed it in 2022

#

it's an extern call

lean sail
river kelp
#

you just write "transform.position" right?

swift comet
#

As far as I see it, you would cache it yourself if you use it in update or whatever frequently, otherwise its not really a bother.

river kelp
#

Still, it will never show up in the profiler, was my point

hollow hound
#

Getting "Cannot find action map 'actionMapName' in actions 'actionsName'" after renaming the action group (using new input system).
Pretty sure its a unity bug. How I can fix it?

topaz sapphire
#

if I wanted to have different functions for different types of weapons (first person shooter), should I A: have a functions that reads and ID and then executes code unique to that weapon type, B: Scripts for each weapon type called individually, C: IDK

river kelp
#

If you have one weapon that shoots blue sparks and one that shoots yellow sparks, A.

#

If you have one weapon that shoots bullets and another that shoots turrets or frogs, B

topaz sapphire
river kelp
#

what is "projectile"

topaz sapphire
#

shoots projectile

#

the rest are hitscan

river kelp
#

I think you can put that in one class

topaz sapphire
#

oh shit

#

i should totally research classes in unity

#

im a moron

swift comet
#

kekwait😊

topaz sapphire
#

why do all those switches when i can use a zero function and call it depending on the weapon type

river kelp
#

Well, unity is not a huge fan of inheritance so y'know

#

you could have a component that hooks up to your shooting class

#

like a component with inheritance on it

topaz sapphire
#

i mean rn its just a script that hitscans from the camera with the rpm and damage referenced from a script holding the ammo, mag and weapon data

#

so it should be easy to add more

#

polymorphism thats the term

#

wdym? like a pannel that can be clicked to change stuff?

hollow hound
topaz sapphire
#

also weapon data (rpm, name, ammo, etc)

#

ok

river kelp
#

basically it just promises a bunch of functionality

#

"I implement the gun interface so I promise you I have the "Shoot" and "Reload" functions."

#

the word "interface" really means like the section of the machine you interact with, and in code it means that you have this method of interacting with this object

#

Basically on a machine that has a "keyboard" interface, you know you can type.
On a class that has a "Fireable" interface, you know you can fire it like a gun.

#

functionally, quite similar to an abstract class

hollow hound
topaz sapphire
#

its been 2 months since ive used classes and the first time in unity

topaz sapphire
#

little rusty

river kelp
#

it's more composition based

#

I really really fought against unity at first, really wanting to use inheritance, and I suffered for it.

#

You're better off just accepting composition and components

topaz sapphire
river kelp
#

We are now enemies for life

topaz sapphire
#

terry davis dint die for this man

river kelp
#

But, there are a lot of things that are very easy with composition but quite hard with inheritance

#

if your objects are clearly defined and have little overlap between them, inheritance is good. If your objects have random sets of functionality, composition is good

#

Like if some enemies fly, some enemies walk, some enemies have HP, some barrels have HP but can't walk, etc. Composition is fantastic

topaz sapphire
#

designed on concept good for random generation

#

not good at en mass random generation

hollow hound
# river kelp You'd have to show the code

There is no error in my code. Action maps look like this, I am using it like

_playerInput.GameInputs.Attack.started += HandleAttackInputStart;

No errors here.
I am getting "Cannot find action map 'Game' in actions 'PlayerInputBase (UnityEngine.InputSystem.InputActionAsset)'", second screenshot shows the place error from

topaz sapphire
#

idk i just hear instances of indie games struggling with random gen bc unity

hollow hound
#

What is NIS?

river kelp
topaz sapphire
hollow hound
#
_playerInput.GameInputs.Dash.started += HandleDashInputStart;

            _playerInput.GameInputs.Kaze.started += HandleKazeInputStart;
            _playerInput.GameInputs.Kaze.canceled += HandleKazeInputEnd;

            _playerInput.GameInputs.Attack.started += HandleAttackInputStart;
            _playerInput.GameInputs.Attack.canceled += HandleAttackInputEnd;

            _playerInput.GameInputs.CursorMove.performed += HandleCursorMove;

            _playerInput.GameInputs.Movement.performed += HandleMovementInputPerformed;
            _playerInput.GameInputs.Movement.canceled += HandleMovementInputEnd;

            _playerInput.GameInputs.WeaponSwitch.started += HandleWeaponSwitchInputStart;
            _playerInput.GameInputs.Reload.started += HandleReloadInputStart;
topaz sapphire
#

what game was it again

#

caves of qud?

river kelp
#

Oh, caves of qud is kind of

topaz sapphire
#

old

river kelp
#

like, for 99% of all games created by humanity

#

random gen is fine with unity

#

for fucken, dwarf fortress, I dunno if it can handle it. Not really because the random gen more because of how big the world is

#

I don't see where you are setting the ID

#

"Cannot find action map 'Game'"

#

"GameInputs"

hollow hound
river kelp
#

don't those ID's need to match

cedar mist
#

How do i make a scene load when the player enters an area and unload the previous scene

hollow hound
#
 _playerInput = new();
 _playerInput.GameInputs.Enable();
#

Method param, yea

 void HandleAttackInputStart(InputAction.CallbackContext context)
river kelp
#

isn't your action map "GameInputs"

hollow hound
#

Yes, creation and enabling in awake, subscription in onEnable.
It worked fine with all this code before renaming. I renamed all my usage of it accordingly. Unity just doesn't want to correctly update info about it, I need a way to reset this somehow,

hollow hound
#

Any idea how I can force it to save it? I tried to regenerate input class but no luck

river kelp
#

so this is not your code, yeah? It's just where you are getting the bug

hollow hound
smoky ibex
#

I am following a tutorial, and theres this datatype the guy uses called "Action" what is it?

river kelp
#

well, basically a function

hollow hound
#

I'm using 2021.3, maybe it changed

river kelp
smoky ibex
#

Ok, one other question

#

What does this syntax mean?

action?.Invoke();

I understand the Invoke(); part, but why the question mark?

river kelp
#

it doesn't do it if it's null

smoky ibex
#

Ok

#

I understand now

#

Thanks

river kelp
#

You can use that for other things too

somber nacelle
river kelp
#

Unity objects don't like it?

#

because they have a special null?

somber nacelle
#

exactly. it doesn't call the overloaded == operator that unity uses to check if something is destroyed

river kelp
#

so since the underlying object is not actually null

#

it gets called, even though you probably expect it to be null at that point

#

like the object is destroyed

somber nacelle
#

yep and you end up with a missing reference exception

hollow hound
river kelp
#

Alright. Never liked the ? operator anyway

#

it's rough to skim

#

myObject?.reference?.reference?.functioncall();

somber nacelle
river kelp
#

Can you use it in the other way? Like the non-direct access way

#

target ? target.position : Vector3.zero;

somber nacelle
#

that's a different operator, that's the ternary operator

#

in this case if target is a UnityEngine.Object it has an implicit cast to bool that does a null check so doing that is perfectly fine since that side of the operator expects a bool

river kelp
#

both functionally and syntactically very similar though

#

myObject?. checks for truth in the reference, any reference other than null is "true", right?

somber nacelle
#

no, that does not check a bool, it checks if the object is null. the ternary operator expects a bool on the left. it just so happens that unity gave UnityEngine.Object an implicit cast to bool

hollow hound
river kelp
somber nacelle
lean sail
river kelp
#

checking if a ref is null or if a bool is true is the same operation, really

somber nacelle
hollow hound
river kelp
#

wacky c++

lean sail
river kelp
#

insane python

lean sail
#

idk why it went to the 2020 version on google, but u can change it to 2023.2 even, still the same-ish message

hollow hound
somber nacelle
#

you can destroy a component without destroying the entire gameobject

#

if you know for sure that both objects will be destroyed at the same time, then sure you can use the null conditional operator. but if you decide to change things so that it isn't 100% guaranteed that the code using the null conditional operator will not run at all after the object is destroyed then you absolutely should use the == operator to check for null instead of the null conditional operator

hollow hound
rugged goblet
#

"Cheaper"?

somber nacelle
#

micro optimization at best, and one that isn't even worth the hassle of ensuring it won't break over just checking for null the way unity wants/expects you to

river kelp
#

Is there a performance difference?

lean sail
#

if your null checks are seriously causing any noticeable performance difference, you have bigger issues

rugged goblet
#

Null check is null check

somber nacelle
river kelp
#

Ah, apparently it doesn't matter.

lean sail
#

this is like when someone said a reverse for loop was slower

river kelp
#

"?." is basically compiled into a normal if check

rugged goblet
#

It's just syntactic sugar

river kelp
#

left here being the code, right being the "compiled"

#

as you can see, they are identical

somber nacelle
#

right but this is in reference to using it for unityengine.objects which has an overloaded == operator that includes some casting. so ?. probably is faster, but not really but any measure that matters

rugged goblet
#

Nanoseconds faster but also prone to being wrong under certain circumstances

river kelp
#

Ah, so in theory if you really wanted to avoid the custom ==

#

But at the cost of being at the mercy of the C++ backend for whether or not you crash

rugged goblet
#

Can't imagine why you'd want to bypass their custom equality check, but there might be some obscure reason

river kelp
#

Never stop fighting against unity and their unity object tyranny. Force C# Objects, normal null checks, equality for all

wide terrace
#

Topple the hierarchy ✊

urban estuary
#

Thanks mao I actually think I know what i did wrong i didn't instruct the script to apply the new shared material to the rigid body

boreal condor
#

Hey, i am using a custom editor script and using OnSceneGUI, but it doesn't render every frame, i have to update something in the scene for it to be called, what alternatives do i have? I'm unable to look for information, whatever i find is obsolete or just doesn't work

cosmic rain
boreal condor
cosmic rain
boreal condor
#

inside OnSceneGUI

#

or wherever you need to reload gizmos/editor visuals i guess 🤔

#

so in my case that would be pretty much every frame

mystic fox
#

Hi, I'm having a problem with the readiness of components on the Editor (works perfectly) vs Built exe... Is like in the .exe the components I rely on being ready are not ready and my game fails to initialize... is there any tip or guide on how to deal with this? Using v2020.3.27

leaden ice
#

Just make sure you do self initialization in Awake and initialization that depends on other objects in Start

gleaming peak
#

can anyone help me out? Ive been working on an android app that is pretty much all just UI, and i was just working on some scripts and now, for whatever reason, i cant click anything in-game

i think maybe it might be related to multiplayer but i literally have no idea what's causing the issue, what should i do?
kinda freaking out :,)
like everything was fine and then, next thing, im compiling the game for the 1000th time and now its like the game isn't even listening to any inputs

#

(not sure where to post this problem so ill post it here too)

somber nacelle
#

if it's all UI and is suddenly not working then make sure that you didn't delete the EventSystem from the scene

gleaming peak
#

oh my god its literally the most basic thing, of course

#

thank you :,)

#

i cant believe THATS what was causing all this panic im embarassed lmao

#

i just accidentally disabled it while testing apparently

dusky lake
#

Anybody familiar with the new multiplayer play mode feature? It just freezes on me in a fresh project, all players except the main editor dont show up and their consoles freeze, no error or anything, also nothing really going on in the project as its just out of the box a fresh project created 5 mins ago

dusky lake
leaden ice
dusky lake
#

No

#

and i didnt use the script at first test either

#
using UnityEngine;

public class RotateBehaviour : MonoBehaviour
{
    void Update()
    {
        transform.rotation *= Quaternion.Euler(360 * Time.deltaTime, 0, 0);
    }
}
#

thats all it does

leaden ice
#

Ok, well I've actually never heard of this feature

#

Is it experimental still?

dusky lake
#

Yes

leaden ice
#

Sounds like it's not quite ready for prime time 😉

dusky lake
#

Yeah im aware, just wanted to test it and thought maybe anybody knows a quick solution

#

better than not trying

forest swan
#

Hello I keep getting this message is there anyway I can fix it? It is a simple movement code and a easy fix but I am new to code and don't know what to do. Can someone Help me?

#

my code

somber nacelle
#

configure your !IDE as you have already been instructed to.

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.

leaden ice
forest swan
somber nacelle
somber nacelle
forest swan
#

I do not understand

somber nacelle
#

it is a step-by-step guide that can even be localized to your preferred language if you do not understand english. follow the guide to configure visual studio

forest swan
#

my language is not on there

somber nacelle
#

then use a translator to follow the guide. having a configured IDE is a requirement to receive help here

forest swan
#

cant reasd the pictures

#

reader

somber nacelle
#

well it's a good thing that the pictures are in the same language your visual studio install is in

forest swan
#

traslated

modern grotto
#

What's a good way to implement status effects in my game?
I have a character that runs around and shoots multiple projectile types, and I want each type of projectile to apply a unique status effect to the enemies it hits (slow, stun, bleed, etc) and I also want to include other status effects like immunity.
What's a good approach to do this?

shell scarab
#

Any help with an index out of range exception?

        void OpenSpace(Index index)
        {
            int limit = index.IsFromEnd ? (values.Length - 1) - index.Value : index.Value;

            for (int i = 0; i < nextIndex - limit; i++)
            {
                values[^i] = values[^(i + 1)];
            }
            values[index] = default;
        }

index.Value = 0, index.isFromEnd = false
limit = 0, nextIndex = 1, i = 0, values.Count = 6

I feel like there shouldn't be an out of range exception here.

somber nacelle
#

array[^0] is the same as array[array.Length]
if you're gonna index from the end, start at 1

shell scarab
#

oh, that makes sense then.

vernal compass
#

Hey I'm trying to create a Scriptable Object and one of the variables I wanted to add was a Date, so that later I could organize all objects by that date! So far I haven't found a good way to store the date as a variable tho, is there a variable type for that?

ashen yoke
#

DateTime.Parse()

#

serializes deserializes

#

i ve read again it seems you dont know of DateTime at all, study it

vernal compass
#

Thank you, I'll look into it!

leaden solstice
#

Is that field for comment purpose like due date?

vernal compass
deep oyster
#

Which part of this is the problem?

leaden solstice
vernal compass
leaden solstice
quartz folio
#

There are multiple issues, that is only one of them

deep oyster
#

What are the other issues :(

quartz folio
#

Go through my link and look.

#

Do not disregard capitalisation.

deep oyster
#

ok, someone somewhere else said 'put it in the resources folder'. Well I changed Resources to a capital R, it didn't change anything

leaden solstice
#

I never actually tried resources folder

quartz folio
#

Why the hell would you 😛

deep oyster
#

also for some reason using the fireball moves my player one space to the left monkas

mystic fox
leaden solstice
#

The function looks very odd that it has to find player by name

leaden ice
#

Yeah... Find abuse!

smoky ibex
#

To find the number of gameObjects with a tag, you'd use GameObject.FindGameObjectsWithTag(); but it returns an array, so I add .Length to it. But there's still a problem, if i store the length in a variable, lets say ObjCount, destroy a few objects with the tag, the value of ObjCount goes up, but doesnt come down. Are there any other methods / functions that give the number of GameObjects with a tag in unity?

deep oyster
smoky ibex
leaden ice
deep oyster
quartz folio
smoky ibex
#

Lemme send screenshot

mystic fox
leaden solstice
leaden ice
#

You should really just use your own list to track your objects rather than using stuff like FindObjectsWithTag

leaden ice
mystic fox
#

@deep oyster Don't let player projectiles hit player

smoky ibex
dusk apex
#

He may be trying to say the value will be higher than what it's supposed to be.

leaden ice
smoky ibex
#
void Update()
    {
        SphereCount = GameObject.FindGameObjectsWithTag("Target").Length;  //<-----This line
        Debug.Log(SphereCount);
        if(CanSpawn && SphereCount < MaxSphereCount)
        {
            MakeRandomSpawnPos();
            Instantiate(Object, SpawnPos, Quaternion.identity);
            CanSpawn = false;
            Invoke(nameof(ResetDelay), Delay);
        }
    }
deep oyster
smoky ibex
#

I have prefabs being created

mystic fox
leaden ice
smoky ibex
#

Im making an AimLabs type thing

leaden solstice
#

Tag and Invoke and naming

#

just makes me sad

leaden ice
#

When they're Destroyed, you'll find fewer objects

leaden ice
#

But this is all very inefficient

smoky ibex
#

What should i do instead

leaden ice
#

Use your own list

dusk apex
leaden ice
#

A whole array being allocated every frame too

smoky ibex
#

Wouldnt it be better to have an int increment each time an object is created

leaden ice
#

Yes, that would be much better than the current approach

leaden solstice
#

It's hard to say anything is nice here

#

Please don't name your variable Object

smoky ibex
#

Why not

leaden solstice
#

Because it is used by both Unity and C#

leaden ice
#

It clashes with System.Object and UnityEngine.Object

smoky ibex
#

How do yall get that box around your text?

smoky ibex
leaden solstice
#

Also it gives no information about your variable

quartz folio
#

`code`

leaden solstice
#

Surround your text with backtick

smoky ibex
#

ahh

smoky ibex
dusk apex
#

What kind of prefab is it?

leaden solstice
#

It's better, but being specific would be better-er

smoky ibex
dusk apex
#

Be descriptive

smoky ibex
#

I thought it was just prefab

quartz folio
#

the only reason that's not great is that prefabs tend to only ever be spawned, they have little use otherwise, so ToSpawn is communicating nothing

dusk apex
leaden solstice
#

fireballPrefab for example

smoky ibex
#

Ah

dusk apex
#

EnemyFish

ashen yoke
#

or SpawnFireball(GameObject prefab)

smoky ibex
#

AimTargetPrefab

#

Since its a target

leaden solstice
#

This kind 🎯 ? Sure

smoky ibex
#

Yes

leaden solstice
#

Conventionally fields starts with lowercase but that's up to project

smoky ibex
#

So how can i keep track of the number of GameObjects with a certain tag?

leaden solstice
#

It's better to manage yourself, using List<GameObject> for example

ashen yoke
#

its better to use components

#

@smoky ibex example of the tag you are interested in?

#

AimTarget?

leaden solstice
#

Sure, if you have a specific script type use it

smoky ibex
#

Its hard to follow when 3 people are helping you at once 😅

ashen yoke
#

class TrackedObject : MonoBehaviour
{
    void OnEnable() => ObjectTracking.Register(this);
    void OnDisable() => ObjectTracking.Unregister(this);
}

class ObjectTracking : MonoBehaviour
{
    private Dictionary<Type, List<MonoBehaviour>> trackedObjects;

    public void Register(MonoBehaviour mb)
    {
         if(!trackedObjects.TryGetValue(mb.GetType(), out var list)
        {
            trackedObjects[mb.GetType()] = list = new List<MonoBehaviour>();
        }

        list.Add(mb);
    }
}
#

barebones example

#

to get count you simply

public int GetCount(Type type)
{
    return trackedObjects[type].Count;
}
#

no tags, all automatic

#

failed with type

#

you should inherit that one

leaden solstice
#

Is it supposed to be static? Hm

ashen yoke
#

what

#

yes

#

lol

#

supposed to be singleton

smoky ibex
#

Uhhhhhhhhhhhhhhhhhhhhh

ashen yoke
#

nevermind then

smoky ibex
#

I aint not be understanding this

#

Code

ashen yoke
#

specify what you dont understand

smoky ibex
#

The whole thing, but thats because im inexperienced lmao

ashen yoke
#

ignore it then

smoky ibex
#

So dont implement it?

ashen yoke
#

i assumed you would understand this as an example of an approach

#

making it actually works requires a level that would click for you

#

so you can actually implement it from an example concept

#

otherwise you are in for a ride

#

in any case you know what is a singleton?

smoky ibex
#

No

#

I am new to c#

ashen yoke
#

alright, do you have any "manager" object in the scene? where various "managers/systems" are?

#

that supposed to be present always

#

each as a single instance

smoky ibex
#

I dont think so

ashen yoke
#

so currently your game is assortments of components scattered and doing their own thing

smoky ibex
#

Yep

lyric moon
#

hey uh

#

if i try and set a key on a dictionary that doesnt exist, will it create that key or will it return an error

lyric moon
#

like
dict[key] = value;

ashen yoke
#

it will override whatever value is in [key]

#

silently

lyric moon
#

what if that key hasnt been used before

#

like its not in the dictionary

ashen yoke
#

it will create it

lyric moon
#

will it add the key or will it error

#

okay good, ty

ashen yoke
#

its a "safe" method

#

"safe" because it wont complain if its already present

ashen yoke
#

there ObjectTracking acts as a "manager" its supposed to be present as a single instance, and manage a lot of other objects

smoky ibex
#

Ahh

ashen yoke
#

other names for it are "controller/system"

smoky ibex
#

So you make a manager for keeping track of objects, then the gameobject creating the targets communicates with it to know how many to spawn?

ashen yoke
#

essentially

#

objects register themselves in the manager

smoky ibex
#

What does that mean

ashen yoke
#
class TrackedObject : MonoBehaviour
{
    void OnEnable() => ObjectTracking.Register(this);
    void OnDisable() => ObjectTracking.Unregister(this);
}
#

when this component is enabled, it will register itself

#

when disabled unregister

smoky ibex
#

But what does registering do?

ashen yoke
#

see code in the example

smoky ibex
#

Thats what i dont understand

ashen yoke
#

what precisely

smoky ibex
#

The register method

ashen yoke
#

point at a term and say - i dont understand this one

#

break it down

smoky ibex
#

Im trying

#

Again, i've only been using unity for a bit

#

idk much

ashen yoke
#

i understand

#

im also explaining how to turn then unknown into known

#

break it down into parts, learn one part after another

#

eventually all becomes known

smoky ibex
#

What is TryGetValue?

ashen yoke
#

method of Dictionary

#

safe way to retreive something from it

smoky ibex
#

Btw you missing a ) in that line

ashen yoke
#

ill cut myself some slack

smoky ibex
#

Okay lol

#

SO

#

So, what about the line trackedObjects[mb.GetType()] = list = new List<MonoBehaviour>(); Why are there 2 = signs?

ashen yoke
#

the TryGetValue(mb.GetType(), out var list)

#

has out keyword

#

this is a c# feature that allows to create a variable in place of its declaration, among other things

smoky ibex
#

I understand that

ashen yoke
#

so out var list created a variable list

#

ok

#

then that line means

smoky ibex
#

I've seen it in Physics.Raycast

ashen yoke
#

that line does exactly the same as

list = new List<MonoBehaviour>();
trackedObjects[mb.GetType()] = list;
#

since the assignements can be chained, given that operations return something

#

it is evaluated right to left

smoky ibex
#

Okay, but how does this, in the end, tell me how many objects (that are somehow classed by name or tag) are in the scene?

ashen yoke
#
public int GetCount(Type type)
{
    return trackedObjects[type].Count;
}
smoky ibex
#

What is Type?

ashen yoke
#

well, its a vast topic but ok

#

most languages that have "classes"

#

are based on a thing called "type system"

smoky ibex
#

I know what a datatype is

ashen yoke
#

where a type is something that can be object

smoky ibex
#

Like int, float, char?

ashen yoke
#

so a class is a "type", a struct is a "type"

leaden ice
leaden solstice
#

Meta

leaden ice
#

to do stuff like .cache is explaining

ashen yoke
#

so Type object stores all that type metadata

#

and is used to indentify types

#

well not stores all of it

#

its more of a handle

#

you can get all methods, properties etc through it

#

or like here you can use it to identify objects

leaden ice
# smoky ibex Why???

C# allows something called "Reflection" which means basially the program can inspect itself. In order to do that you need to be able to represent a datatype in a variable. So you can say like "the type of this field is int" and express that in code

#

there are also datatypes for Methods, Fields, etc - all the pieces of the program.

ashen yoke
#

ie if you do print( collider.GetType().Name) it will print something like "UnityEngine.Physics.Collider"

#

yes

leaden ice
smoky ibex
#

Ahh

leaden ice
#

Type t = typeof(int);

#

now t contains the int type

ashen yoke
#

typeof resolves Type at compile time

smoky ibex
#

Oh okay yeah

ashen yoke
#

since every Type reference is unique per type, you can use it as keys in dictionaries

smoky ibex
#

So, when i register something, Type becomes the type of what i registered?

ashen yoke
#

not sure how to interpret this question

#

becomes the type

smoky ibex
#

Uhhh

minor storm
#

im not sure if this is a coding thing but if i have bullets that stick to my character (or around my character) and they get stuck, how would i make the bullets phase through my player but not a wall

smoky ibex
#

this ended up being much more complicated than i anticipated

cosmic ermine
#

what is the correct way to setup the indices of a quad (2 triangles)? If I'm reading my code correctly this should be what the indices look like (the paint sketch), but as you can see in the screenshot I instead seem to not have that, and also 1 of the tris is rendering the other way round for some reason.... What am I missing lol?

int VertexStart = i * 4; // if every tile takes up 4 vertices then we use i * 4 to get the correct starting vertex
int IndexStart = i * 6; // read above and replace some words, and you might understand my nonsense

UnsafeElementAt(Vertices, VertexStart).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(0.5f, 0.5f, 0); // top right
UnsafeElementAt(Vertices, VertexStart).UV = BlockInfo.UV + new float2(SpriteWidth, SpriteHeight);

UnsafeElementAt(Vertices, VertexStart + 1).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(-0.5f, -0.5f, 0); // bottom right
UnsafeElementAt(Vertices, VertexStart + 1).UV = BlockInfo.UV + new float2(SpriteWidth, 0);

UnsafeElementAt(Vertices, VertexStart + 2).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(-0.5f, 0.5f, 0); // top left
UnsafeElementAt(Vertices, VertexStart + 2).UV = BlockInfo.UV + new float2(0, SpriteHeight);

UnsafeElementAt(Vertices, VertexStart + 3).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(0.5f, -0.5f, 0); // bottom left
UnsafeElementAt(Vertices, VertexStart + 3).UV = BlockInfo.UV;

uint UVertexStart = (uint)VertexStart;

Indices[IndexStart] = UVertexStart;
Indices[IndexStart + 1] = UVertexStart + 1;
Indices[IndexStart + 2] = UVertexStart + 2;

Indices[IndexStart + 3] = UVertexStart + 1;
Indices[IndexStart + 4] = UVertexStart + 3;
Indices[IndexStart + 5] = UVertexStart + 2;
ashen yoke
smoky ibex
ashen yoke
#

you have arrows, just flip diagonal direction

cosmic ermine
#

I shall try that thanks!

ashen yoke
#

i dont know precise winding order, but i always got around just by flipping until it works lol

leaden ice
#

wouldn't that be bottom left?

#

float3(0.5f, -0.5f, 0); would be bottom right

cosmic ermine
leaden ice
#

and vice versa for float3(0.5f, -0.5f, 0); // bottom left, but you probably see that now too

idle flax
#

I have a script that writes this file to json, however "SerializeableTemperature" and "SerializableCondiment" gets included in the json file even if they're null. Is there any way I can only include them if a script initializes a new instance of them?

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

[System.Serializable]
public class SerializableObject
{
    public bool instantiatedDuringRuntime;
    public string id;
    public int prefabId;

    //Basic info
    public Vector3 position;
    public Quaternion rotation;

    //Temperature
    public SerializableTemperature temperature;

    //Capacity
    public SerializableCondiment condiment;
    //Status
    public bool status;

    public SerializableObject()
    {
        instantiatedDuringRuntime = false;
        id = "";
        temperature = null;
        position = new Vector3();
        rotation = new Quaternion();
        condiment = null;
        status = false;
    }

}
ashen yoke
#

Json.Net has a flag in its settings object

plucky inlet
ashen yoke
#

on how to treat null, read docs

plucky inlet
#

Double Strike 😄

ashen yoke
#

thats per prop, there is global

idle flax
#

No json lib, I just use Unity's build in.

ashen yoke
#

well

#

WELL

#

enjoy

rain minnow
#

Don't use that (default) one . . .

idle flax
#

It's working fine for what I need it for.

ashen yoke
#

weird that you came here asking questions then

plucky inlet
#

And here we are telling you, that it does not deliver what you need it for right now 😄

#

Just switch to newtonsoft, its already in there in Unity latest versions I think.

idle flax
#

So I need to rewrite my code entirely just to do this one thing?

plucky inlet
#

You have one line that says, Convert or Deserialize or whatever.

ashen yoke
#

rewrite entirely?

plucky inlet
#

Rewrite that, same for other conversions

ashen yoke
#

you mean rewrite 2 Serialize/Deserialize calls?

plucky inlet
#

Its just the suggestion from this channel, use it or not. If you can live with a null object, which is fine too if you handle it correctly, stick to it. Just think a bit further that there might be more cases where you need some "advanced" functions

ashen yoke
#

the issue is that you dont want to learn new library, but you require features that are not available in the one you know

#

solve the issue of not wanting to learn new library

#

start wanting to learn it

#

and its a smooth sailing

idle flax
#

Sorry, I've never used a json library, don't know how it works.
It's not that I don't want to learn it, it would just be easier if I didn't have to since Unity's built in has been working perfectly for me up until this point.

#

But if there's no other way then I guess I'll have to look into it.

ashen yoke
#

here are the benefits, some of them

#

unity one is a rudimentary, blackboxed lib with no customization

plucky inlet
#

Its just one line of "using NewtonsoftJson" or something and then you just conver tyour JsonUtility.ToJson or how its called to the newtonsoft call, you find in the docs easily. Nothing more to do there and then you can use what you need from all the features

ashen yoke
#

json.net you get full source, you get intermediary objects, you can add custom serialization routines for any type, you can customize it through api or source

#

you can do miracles with it

idle flax
#

All right then, thanks.

plucky inlet
#

And just think ahead. if you go into development, you might be fine with your solution in your personal project right now. But if you want to learn to work on other projects and within teams, you wont meet that builtin json again probably

lyric moon
ashen yoke
#

Nullable<long>

lyric moon
#

i know long? is a nullable long but

#

why cant i set my long to a value thats nullable

ashen yoke
#

show code

lyric moon
#

im tryna set a long to a long? and it dont like that

ashen yoke
#

GetLong().Value

#

there is no implicit cast

lyric moon
ashen yoke
#

you also have to check GetLong().HasValue

#

my guess its the purpose of being nullable there

#

as an indicator of whether or not the value was present

#

which is bad api, a bool TryGetLong(out long) would be better

daring spade
#

Can anyone help me i keep getting a error saying The type name OnFootActions does not exist in type PlayerInput

plucky inlet
daring spade
plucky inlet
daring spade
#

i did

ashen yoke
#

you didnt

ashen yoke
#

can i get object path in hierarchy?

#

anything built in for that

simple sable
#

Hey. I have quick question.

I have a script that has some variables set as [SerializeField] since I want to assign them in the inspector. However, I also have a bool variable that, if false, the logic that uses those variables is not used.

So, my question would be if there is a way to, based on that bool, hide those variables from the inspector.

rain minnow
simple sable
#

I'll look into it, thanks.

latent latch
#

custom inspector is an annoyance if you're constantly expanding on your data since you'll always have to edit that too to reflect changes. It's unfortunate that NaughtyAttributes is the best alternative that's free because there's still much to be desired when it comes to quick implementation of data.

rain minnow
ashen yoke
#
        private static StringBuilder _getGameObjectPathSB = new StringBuilder();
        public static string GetGameObjectPath(this Transform tr)
        {
            _getGameObjectPathSB.Clear();
            int depth = 0;
            void ConstructPath(Transform transform)
            {
                depth++;
                if (transform.parent != null)
                    ConstructPath(transform.parent);

                if (depth != 1)
                    _getGameObjectPathSB.Append(transform.name).Append('.');
            }

            ConstructPath(tr);
            return _getGameObjectPathSB.ToString();
        }
#

i think this will work

#

forgot to - depth

steady moat
#

This is what I use (For Debug Only):

        private static string GetPath(this Transform current)
        {
            if (current.parent == null)
                return "/" + current.name;
            return current.parent.GetPath() + "/" + current.name;
        }
ashen yoke
#

that is much better

#

elegancy wise

leaden solstice
#
sb.Append(tr.name);
while (tr.parent) {
   sb.Insert(0, ‘/‘);
   sb.Insert(0, tr.parent.name);
   tr = tr.parent;
}
ashen yoke
#

also better

#

both are less efficient

leaden solstice
#

Append then somehow reverse 😄

fierce osprey
#

Hello, I have a list of structs. The list has a lot of entries, and I want to be able to add and remove whenever I need to. I need to send this data to a job, however, I do not know how to turn this list into a native collection. I can do this by calling '.ToArray()' and then passing that when creating a NativeArray, but that would allocate memory and would create garbage. Is there an allocation-free like with arrays in creating a native collection from a regular list?

ashen yoke
lost dove
#

Greetings gentlemen, I am writing some code to spawn projectiles around my player, in a symmetrical way based on some angle calculations.
The code is here: https://hastebin.skyra.pw/ujuhamariv.pgsql
I am using a box to demonstrate my problem, as you can see it is not symmetrical at all. I am uncertain why, and I am hoping for some insight.

#

front facing is upwards.

#

i in createProjectile is simply this:

        for (int i = 1; i < config.ProjectilesPerBurst + 1; i++)
            CreateProjectile(i);```
fervent furnace
#

just use nativelist at the very beginning

fierce osprey
#

I load this data from a file and then I write it back to a file later. I could after loading convert the list to a native list but that would mean I would still need to convert the whole list to an array.

leaden solstice
spiral robin
#

Why do i get the following error:

lost dove
#

gameObject, not GameObject.

spiral robin
#

rookie mistake, thanks

leaden solstice
fierce osprey
fervent furnace
#

?

#

a list is array

fierce osprey
leaden solstice
#

Why not the fastest?

lean edge
#

does anyone know why would visual studio code intellisense stop working? i tried everything and nothing works...

rugged goblet
#

Typically a List has an array with a capacity bigger than the list size

fierce osprey
# fervent furnace a list is array

Well yes, but as far as I know the resize operation is expensive so what the list does is just changes the count and leaves the array length as is

rugged goblet
#

Resizing an array consists of making a whole new array of the desired size and copying the contents of the old array

leaden solstice
#

Just loop and copy, foreach is optimized. If you have managed collection convert to native collection a copy is pretty much inevitable

fierce osprey
#

I guess so. I would love a solution like you can do with the arrays public NativeArray<T0>(T[] array, Unity.Collections.Allocator allocator);
But instead just be able to pass a regular list when creating a native list.

#

Oh well

idle flax
#

Got JSON.net working (as well as the ignore null objects setting), thanks for pointing me in the right direction @ashen yoke @plucky inlet .

#

One more question though, my Vector3 looks like this for some reason, any idea why?

"transform": {
        "position": {
          "x": 97.959,
          "y": 0.5990211,
          "z": 0.435000032,
          "normalized": {
            "x": 0.9999714,
            "y": 0.00611484377,
            "z": 0.004440507,
            "normalized": {
              "x": 0.999971449,
              "y": 0.006114844,
              "z": 0.00444050739,
              "magnitude": 1.0,
              "sqrMagnitude": 1.0
            },
            "magnitude": 0.99999994,
            "sqrMagnitude": 0.9999999
          },
          "magnitude": 97.9618,
          "sqrMagnitude": 9596.514
        },
leaden solstice
#

What json serializer are you trying

bold flare
vivid escarp
#

I am creating a simple script for a "Nurse" obj that follows a player, the only issue, it's that when i introduce the LookAt function the Nurse stop working as expected, it starts moving in random direction (sometimes) and not working as without the LookAt function, is anyone that can help me, I have searched through the internet but i couldn't be able to find any solution :C
This is my code


public class NurseMovement : MonoBehaviour
{
    [SerializeField] private float speed = 2.0f;
    private Vector3 _directionPlayer;
    public GameObject player;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void LateUpdate()
    {
        _directionPlayer = player.transform.position - transform.position;
        transform.LookAt(player.transform.position);
        if (_directionPlayer.magnitude > 6)
        {
            Vector3 velocity = _directionPlayer.normalized * (speed * Time.deltaTime);
            transform.Translate(velocity);
        }
    }
}```
rugged goblet
#

Just because nobody solved your problem the first time doesn't mean you copy and paste it and spam it

vivid escarp
#

gif

ashen yoke
#

by default there is no "default" serialization for vector 3