#archived-code-general

1 messages · Page 296 of 1

agile carbon
#

@quartz folio would this approach work as well (this is in a different language for testing purposes) ```lua
local lookVector = Vector3.new(1, 0, 0) -- Replace with your actual lookvector

-- Choose any vector that is not parallel to the lookvector
local arbitraryVector = Vector3.new(0, 1, 0)

-- Calculate the perpendicular vector using the cross product
local perpendicularVector = lookVector:Cross(arbitraryVector)

-- Calculate the magnitude of the perpendicular vector
local magnitude = perpendicularVector.Magnitude

print(magnitude)```

quartz folio
#

No

#

What it's describing is simple, I don't understand what you're really struggling with

rich leaf
#

How can i create a serializzer for a type?

agile carbon
#

but i was trying to see if my way was valid by looking at other approaches

quartz folio
#

where is the velocity being used here?

agile carbon
#

is the velocity

quartz folio
#

So why are you getting a vector perpendicular to the velocity

agile carbon
#

rn my forwardVector is in fact the blue vector

#

i need to get the orange one sec

agile carbon
#

okay so the forwardVector is now the orange line, the wheelDirection is now the blueLine and the perpendicularDirection is now the red line

#

So now I am doing the dot between the orange vector and then the direction of the right. does this look good?

#

then i can transfer this to unity

merry stream
#

So I'm making an ability system in unity similar to GAS in Unreal and was wondering if i should make the main "ability system component" that would be on a character calculate their stats every frame (ie calculate what they would be responding to active effects like 25% slowness) or try to do it it in a way that sends events to update the stats only when an effect is added. though i forsee stats not updatinng and annoying edge cases from the second method albeit better performance, what is recommended?

spring creek
#

You should have gone over it a bit in middle school and early highschool in 2 dimensions. You have a graph. You move three units right, three units up. Finding the hypotenuse is the same as finding a 2d magnitude here.
A^2 + B^2 = C^2
3^2 + 3^2 = C^2
9 + 9 = C^2
18 = C^2
sqrt(18) = C
C = ~4.24

#

2d and 3d vectors are just offsets from some point

agile carbon
#

i already have the hypotenuse

#

in ur example im trying to find the magnitude of the x axis vector

spring creek
somber nacelle
#

the magnitude of a single float (like a single axis of a vector3) is just the absolute value of that float

agile carbon
# somber nacelle the magnitude of a single float (like a single axis of a vector3) is just the ab...

A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy

~ More from Toyful Games ~

▶ Play video
#

look at the part it talks about

#

i have the orange vector (direction and magnitude) and in my code i calculate the direction of the red arrow but i dont have its magnitude

#

im trying to find the magnitude of that red arrow

spring creek
agile carbon
spring creek
#

the magnitude of a single float (like a single axis of a vector3) is just the absolute value of that float

agile carbon
#

This is the problem

#

I haven’t leaned vectors so that’s why idk what I’m doing with dot

spring creek
#

The paper doesn't really help explain whay you want though

#

I will read above to get clued in

#

Honestly, I'm really confused. Vertx explained it better than I ever could, and even gave code for it. What part is still causing an issue?

agile carbon
#

I’ll keep experimenting

dark kindle
#

what it look like is ur trying to break down the angled vector into x and y component?

#

and u need the x from the x and y component, i think

dark kindle
#

ok this might help a bit as i asked question converting magnitude and angle into x and y. it could be related so take it grains of salts

#

asked about 8/2023

#

it was a random ball generator for a pong project i had

quartz folio
#

!collab

tawny elkBOT
agile carbon
dark kindle
#

ok

#

dot product im assuming

agile carbon
past kite
#

I have 4500 GOs and 500 RB2Ds in a scene and see significant performance loss (Physics2DFixedUpdate; specifically the solver). 500 RBs is not even the target as I'm just prototyping right now. Do I immediately have to learn DOTS or how can I rule out newbie mistakes?

somber nacelle
#

that is a lot of bodies, you probably would want to use dots for that, though i don't think there is a 2d physics solution for dots yet

past kite
#

how do people simulate large crowds of enemies?

cosmic rain
#

It's not too much.
You can still optimize it a bit imho

somber nacelle
peak karma
#

Does anyone know whats wrong with my code? I'm making an FPS game in unity and want the game to end after a set amount of time (I've made it five seconds for testing) but for some reason, it won"t end? I have attached my script and really need ur help : )
https://paste.ofcode.org/njKQts7qUbtQHZzz9iCJyb

cosmic rain
past kite
cosmic rain
#

Though, you'll need to do proper analysis of the bottlenecks to address the issues properly

past kite
#

was hoping I don't have to start early with optimizing. I could enable/disable RBs depending on whether I need physics for them at the moment.

somber nacelle
somber nacelle
cosmic rain
past kite
#

I'm at the moment not using RBs on them, but that would again drastically increase the number of RBs.

cosmic rain
#

You don't need rbs, for simple gravity logic

somber nacelle
#

it's pretty trivial to calculate and apply the gravity manually rather than using a rb for that

peak karma
cosmic rain
peak karma
#

ok ok, leeme rephrase that sry

gentle glen
#

Ain't that out of range?

cosmic rain
peak karma
#

I'm making an FPS game in Unity 2021 LTS and using PHOTON PUN 2 for the networking. The way it works i that once players have joined the room, the host clicks "start" redirecting them all to a unique scene in which they all play. After a set amount of time (I've made it 5 seconds for testing), the game ends, displays a game over text and happy days :). If only

This isn't the case for me and the game is going on FOREVER. I've tried multiple ways to troubleshoot this such as displaying a message in the debug menu when the game is supposed to end, but even then I get no message in the debug menu or an end to the actual game. I have attached my script and a video that shows my problem and really would appreciate your help : )
https://paste.ofcode.org/njKQts7qUbtQHZzz9iCJyb

#

As you can see, the game doesn't end after 5 seconds and the player is just stuck in the scene.

somber nacelle
#

do you have an active Launcher component in the scene

peak karma
#

yes

#

actually, let me check

#

yes i do

somber nacelle
#

show it and the console during play mode after the game should have ended

peak karma
#

ok

somber nacelle
#

also note that you will be starting new instances of your coroutine every single frame for 3 seconds before the game will actually end. though that wouldn't prevent it from ending right now

peak karma
#

It wasn't doing that before...

somber nacelle
#

well the Launcher component is what ends the game. if that component is also in the main menu, then it will do it there too

peak karma
#

ohhhh, so how can i ifx that? make a new scrpt with the code im guessing?

somber nacelle
#

yes

#

and only put that component into scenes where you want that functionality

peak karma
#

ok

cosmic rain
#

Honestly, I suggest you start with a simpler single player game. Follow the unity !learn beginner pathways to get the hang of the basics. Networking is not something a beginner should mess with.

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

toxic vault
#

JFC!!!!! I solved my aiming issues

For some damn reason my player prefab had multiple "bulletspawn" objects on them. One directly attached to their Hand_Right_jnt, one on a disabled RPG_weapon on their body, and the actual one attached to their equipped weapon

I had those other ones disabled, but my GameObject.Find() in script was finding the wrong one.

And it was close enough to not trigger any red flags, but far away enough to make aiming go off to pull my hair out

somber nacelle
toxic vault
#

Yeah, but I equip weapons at runtime and attach to the player object. So the bulletspawn objects (children of weapon object) has to be figured out at realtime

#

So the next issue is that I don't make my cursor the exact target (since then my bullets hit the ground). I instead make the target a certain height above ground so it hits zombies in the chest. But this means, my cursor could be at blue and my bullets seem to pass through red. This makes it feel aiming is off.

Ideas on how to deal with this since it's not a true top-down game, but at this slight angle?

leaden ice
somber nacelle
runic nimbus
#

My bad, new to this server

crisp flower
#

The quest 3 generates a mesh but it doesn't apply any UV coordinates to it. I want coords on it. The mesh is supplied to the application at runtime. In a best case scenario, I could have a non-overlapping UV unwrap. Pipe dream. Failing that, even a box projection, or an unwrap/peel that doesn't mind so much about overlapping. Any ideas?

main pawn
#

Anyone know how to get the distance to the edge of the screen as a percentage, where 100% is a particular point on the screen and 0% is the edge?

sleek bough
#

Math. Use Screen.currentResolution to get the resolution and calculate pointer position or if it's in the world then use Camera's world to screen method

main pawn
sleek bough
#

mouse position if you need pointer

#

Screen.height should be used if you support windowed

#

(Always read the manual for methods to be sure)

main pawn
#

I'm trying to do it for an app

merry stream
#

So I'm making an ability system in unity similar to GAS in Unreal and was wondering if i should make the main "ability system component" that would be on a character calculate their stats every frame (ie calculate what they would be responding to active effects like 25% slowness) or try to do it it in a way that sends events to update the stats only when an effect is added. though i forsee stats not updatinng and annoying edge cases from the second method albeit better performance, what is recommended?

main pawn
#

Here's my code so far:

float distance = Vector3.Distance(d.transform.localPosition, Vector3.zero);
float f = Mathf.InverseLerp(d.transform.localPosition.y, Screen.height, distance);
d.transform.localScale = new Vector3(f, f, f);

#

I'm trying to get the distance between d and vector 0 at the moment.

#

Zero is another local position

#

Basically an icon in a container, and I'm trying to make it shrink the further it is from 0

leaden ice
#

though it's unclear if these are UI elements or game world objects or what

gentle glen
#

Thanks to everyone in this channel
I got my problem solved already

craggy veldt
leaden ice
#

InverseLerp returns a normalized T

#

the inputs are a min, a max, and a value in between

craggy veldt
#

oh yeah, I got mixed there

#

I always do 0 - 1 range for Mathf lerp for some reason 😂

latent latch
#

unless it's something gradual, then I'd group stuff so you're not recalculating everything every frame

main pawn
#

Basically, I want the icons to get larger as they appraoch the centre of the screen, and get smaller as they get closer to the edge

young hound
#

Is there a way to detect spikes in a music track? like if DB >= 90 ??

light wraith
#

hey :)
I need help connecting classes in my architecture:
I have a player which can go through different "player states".
he can have a 2D state where he goes only sideways, a 3D state where he walks normally, or for example a ski state where the controls and movement change entirely.
I build an interface and many inheriting classes for each movement state, and a monobehaviour MovementManager that holds a IMoveState _currentState;
he is responsible for calling update and switching between states.
however I am not sure how to link the InputSystem with the different states. so far I just opened many input events on the Interface and just subscribed through the movementManager.
I am sure there is a much better solution to this 🙃
see graph bellow: (InputManager is the wrapper for the input system events)

mental rover
#

if the maps are fundamentally different, it would probably make more sense to let each state handle its movement directly, and turn MovementManager into a state machine that just enables/disables the states

copper grove
#

I get this error when i try to click on craft button. i dont understand how i fix it.It sbeen quite long.

knotty sun
copper grove
copper grove
#

!code

tawny elkBOT
knotty sun
copper grove
#

wht

#

theres another error

knotty sun
#

that is where the error is happening

copper grove
#

this is the actual problem.that error just appeared lemme look on to it

#

102? means line 102?

knotty sun
#

yes

copper grove
#

thats the line

#

wait i was looking at ther wrong things then

knotty sun
#

so InventorySystem or InventorySystem.Instance are null

copper grove
#

i might be able to correct it now

light wraith
copper grove
#

i just remove inventoryitemlist and directly used inventorysystem.instance.itemlist lets try now

#

now another error caem :/

#

so im back where i started

#

so the problem was

#

the error is this

#

So the craftanyitem is run by axecraftbutton where axeblueprint is used but

#

when i check the craftingmanager.Axe blueprint is not set

#

but idk why and what to do

#

i think its fixed

#

still the same error

mental rover
tawny elkBOT
copper grove
mental rover
# copper grove but idk why and what to do

fwiw I'd think if craftingmanager.Axe is not set then you should probably set it (I know this sounds silly to the point of being rude, but it's really that simple no?)

copper grove
#

code is too long to send here

copper grove
#
public class BluePrint : MonoBehaviour
{
public string itemName;
public string Req1;
public string Req2;

public int Req1Amount;
public int Req2Amount;

public int NumberOfRequirements;

public BluePrint(string name, int reqNUM, int R1Amount, string R1, int R2Amount, string R2)
{
    itemName = name;
    NumberOfRequirements=reqNUM ;
    Req1Amount=R1Amount  ;
   Req1= R1  ;
   Req2Amount= R2Amount  ;
   Req2= R2      ;
}
}

And this is the blueprint script

#

public class CraftingSystem : MonoBehaviour
{
    public static CraftingSystem Instance {get; set;}
    private void Awake()
    {
        if(Instance != null && Instance!= this)
        {
            Destroy(gameObject);
        }
        else
        {
        Instance = this;
        }
    }

    public GameObject CraftingUI;
    public GameObject ToolsUI;
    public Button ToolsButton;
    public Button AxeCraftButton;
    public bool isOpen;
    Text AxeReq1, AxeReq2;
    public List<string> InventoryItemList = new List<string>();
    public int StoneCount;
    public int StickCount;
    public BluePrint AxeBlueprint =  new BluePrint("Axe", 2, 3,"Stone", 3, "stick");



    void Start()
    {
        
        isOpen = false;
        ToolsButton = CraftingUI.transform.Find("Tools_button").GetComponent<Button>();
        ToolsButton.onClick.AddListener(delegate{OpenToolsUI();});
        AxeReq1 = ToolsUI.transform.Find("Axe").transform.Find("axeReq1").GetComponent<Text>();
        AxeReq2 = ToolsUI.transform.Find("Axe").transform.Find("axeReq2").GetComponent<Text>();
        AxeCraftButton.onClick.AddListener(delegate{CraftAnyItem(AxeBlueprint);});

    }
    public void CraftAnyItem(BluePrint bluePrintToCraft)    
    {
        InventorySystem.Instance.AddtoInventory(bluePrintToCraft.itemName);
        if(bluePrintToCraft.NumberOfRequirements == 1)
        {
        InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req1, bluePrintToCraft.Req1Amount);
        }
        if(bluePrintToCraft.NumberOfRequirements == 2)
        {
            InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req1, bluePrintToCraft.Req1Amount);
            InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req2, bluePrintToCraft.Req2Amount);
        }
        StartCoroutine(Calculate());

        refreshneededItems();

This is a part of craftingsystem

#
public IEnumerator Calculate()
    {
        yield return new WaitForSeconds(1f);
         InventorySystem.Instance.ReCalculateList();

    }
    public void OpenToolsUI()
    {
        CraftingUI.SetActive(false);
        ToolsUI.SetActive(true);
    }
    


    void Update()
    {
        refreshneededItems();
        if(Input.GetKeyDown(KeyCode.C) && !isOpen)
        {
 

           Cursor.lockState = CursorLockMode.None;  
             CraftingUI.gameObject.SetActive(true);
             isOpen = true;

        }
        else if(Input.GetKeyDown(KeyCode.C)&& isOpen)
        {
            ToolsUI.SetActive(false);
            

            if(InventorySystem.Instance.isOpen == false)
            {
            Cursor.lockState = CursorLockMode.Locked;
            }
            CraftingUI.gameObject.SetActive(false);
              isOpen = false;

        }
    }
    private void refreshneededItems()
    {
         int StoneCount = 0;
         int  StickCount = 0;

        foreach(string item in InventorySystem.Instance.ItemList)
        {
            switch(item)
            {
                case "Stone":
                StoneCount +=1;
                break;
                case "Stick":
                StickCount +=1;
                break;
                

                
            }

        }
        //AxeText Requirements refreshes here
        AxeReq1.text = "3 Stick ["+ StickCount + "]";
         AxeReq2.text = "3 Stone ["+ StoneCount + "]";

         if(StoneCount >= 3 && StickCount >= 3)
         {
            AxeCraftButton.gameObject.SetActive(true);
         }
         else
         {
            AxeCraftButton.gameObject.SetActive(false);
         }

    }
}

and this is the rest

#

the error is here

 public void CraftAnyItem(BluePrint bluePrintToCraft)    
    {
        InventorySystem.Instance.AddtoInventory(bluePrintToCraft.itemName);
        if(bluePrintToCraft.NumberOfRequirements == 1)
        {
        InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req1, bluePrintToCraft.Req1Amount);
        }
        if(bluePrintToCraft.NumberOfRequirements == 2)
        {
            InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req1, bluePrintToCraft.Req1Amount);
            InventorySystem.Instance.RemoveFromInventory(bluePrintToCraft.Req2, bluePrintToCraft.Req2Amount);
        }```
mental rover
#

firstly it would be worth verifying what exactly is null - is it InventorySystem.Instance, bluePrintToCraft?

copper grove
#

how do i check that

mental rover
#

and an initialiser like public BluePrint AxeBlueprint = new BluePrint("Axe", 2, 3,"Stone", 3, "stick"); will be overridden by Unity if something else has been serialized

mental rover
copper grove
#

just debug.log(inventorysystem.instance) just this?

silver vector
#

Physics.Raycast(transform.position + new Vector3(0, 0.25f, 0), transform.forward, out hit_1, attackDistance, TargetLayer);

hi guys can i have this raycast but the transform.forward (direction of the ray) is a world-space axis so it doesn't rotate with the player, how do i like convert it to local-space?

hexed pecan
copper grove
#

could u help me

#

do i take that as a yes or no

#

guys so i found the error but i dont know how i fix it

latent latch
#

neat

copper grove
#

this means AxeBlueprint is null

#

but i dont know why\

simple sable
#

Hey everyone. I have a quick question.

I'm working on a dev console for my game and it's working nicely so far. I'm able to create custom commands, log messages and all that stuff. But, I was thinking that maybe I should also make it so that, whatever logs/warnings/errors get printed in Unity's console to show up in my custom one as well. I imagine that would be nice since when in build you can’t see Unity’s console, obviously.

That works as well, but I'm wondering if it’s a good thing to do. Would accessing Unity’s console slow down the game’s build? (I’m aware that in the final build of the game those logs should be removed so as not to lose performance).

surreal cloak
#

does unity have something like a collider for vision like that already in it cuz coding a vision collider that gets blocked by walls seems like a pain in the ass (sry for the bad paint skills)

copper grove
#

guys.So this is my blueprint script.and 2nd pic is my axe blueprint.I tried cs Debug.Log(AxeBlueprint.name) and it gave me an error telling that its null. So it means that Axeblueprint is null but idk how i fix it could someone pls tell me how i fix it

knotty sun
#

you really should spend some time learing unity basics

copper grove
#

thats exactly what it said but i made it while watching a tutorial and this is exactly what he did

leaden ice
simple sable
leaden ice
#

If the video did this it made a mistake

copper grove
#

but the code is working

leaden ice
#

And probably quietly fixed it off screen

copper grove
#

oh

knotty sun
copper grove
copper grove
leaden ice
#

He didn't

#

It will technically sort of work if you never access .name

#

But it's a terrible idea

#

You should not make it a MonoBehaviour

copper grove
#

ok ill make the blueprint some other way

leaden ice
#

(your debug.log is accessing .name)

copper grove
#

if thats bad

leaden ice
#

Just remove MonoBehaviour from it

#

That's all

copper grove
#

oke

leaden ice
#

Probably find a better tutorial too lol

simple sable
knotty sun
#

@copper grove Do you not get the impression that your learning path is really flawed?

copper grove
knotty sun
#

then you should know how to diagnose and fix a Null Reference Exception which, apparently, you do not

toxic vault
#

Let's take these 2 examples -

#
  1. I aim my cursor at red dot. Am I trying to shoot the plant, or am I trying to hit the zombie? As a player what should I expect?
#
  1. I aim my cursor at green dot (on the plant). But because I fire in the plane of the gun, the bullet actually travels higher towards the blue dot. And player feels his gun is shooting way off from where his cursor was
latent latch
heady iris
#

I'm having trouble profiling an Awaitable async method.

#

I created a profiler marker and put Begin() and End() calls at the start and end of the async method

#

I start it with StartCoroutine(TheAsyncMethod());

#

If I turn on deep profile, I can find the profiler marker

#

but without deep profile on, I can't find it anywhere

neon nymph
#

Help can anyone help me make a isGrounded( ) void to make the player only jump when isGrounded( ) is true and this for a rigidbody

heady iris
#

there is no such thing as "a void".

void Update() { }

This is a method called Update. It returns nothing, so the return type is void.

#

I presume you want a method that returns a bool, since you want it to return true or false...

neon nymph
#

no it's bool i was wrong

heady iris
#

yes, and you said "make a isGrounded() void"

#

ah, ok

#

missed the edit :p

#

most IsGrounded-y methods will do a raycast or a physics query

neon nymph
neon nymph
#

but this for a rigidbody* with a custom mesh

#

Ok how to use raycast on a custom mesh?

#

?👆

ivory vault
#

alr i have for some reason a problem that i cant jump in my game

    private void Update()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatisGround);
        MyInput();
        SpeedControl();

        if (grounded)
            rb.drag = groundDrag;
        else
            rb.drag = 0;
    }
   if(Input.GetKey(jumpKey) && readToJump && grounded)
       {
            Debug.Log("Penis");
            readToJump = false;

            Jump();

            Invoke(nameof(ResetJump), jumpCooldown);
        }
  private void Jump()
    {
        rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    }

    private void ResetJump()
    {
        readToJump = true;
    }
heady iris
#

as can CheckSphere

neon nymph
#

ok

heady iris
neon nymph
#

but how to get the height of a mesh collider?

ivory vault
heady iris
#

the code you posted is completely invalid; you have placed a big blob of code outside of a method

neon nymph
#

bro what do you mean by penis?

heady iris
#

also, consider another debug message.

ivory vault
#

i think the problem is that it doesnt detect that the jumpkey is pressed

heady iris
#

!code

tawny elkBOT
heady iris
#

Do not delete random chunks of code.

#

imagine if someone asked you to fix their car, but pulled out the engine and cut it in half first

ivory vault
neon nymph
#

!mesh Collider

#

!height of mesh collider

heady iris
#

or you have the wrong jumpKey

neon nymph
#

Ok i figured it out it's Collider.bounds.size.y

gusty aurora
#

How do I create a nice looking component like the post-processing volume ?

ivory vault
neon nymph
#

!Physics.Raycast()

#

!code

tawny elkBOT
naive swallow
# neon nymph !Physics.Raycast()

You can't just type anything into the bot and expect it to work. If you want to know what a function does, type it into google and get the documentation that way

ivory vault
#

and its not grounded cause if i do without i still cant jump

heady iris
#

log the variables anyway

neon nymph
#

Hey just to ask i wanna know what should use for a rigidbody jump Rb.MovePosition() or Rb.AddForce()?

ivory vault
heady iris
ivory vault
#

@heady iris im confused

heady iris
#

turn off Collapse so that you see individual log entries

ivory vault
#

im printing it like that ``` private void Log()
{
Debug.Log("grounded"+ grounded);
Debug.Log("ready"+ readyToJump);
}

ivory vault
neon nymph
#

Any opinion for a jump speed

#

a float

ivory vault
neon nymph
#

ok

leaden ice
#

My opinion is you should really clarify what it is. "Jump speed" doesn't seem very meaningful/measurable.
A better idea would be:

  • Max jump height
  • Jump duration
  • Initial jump velocity
neon nymph
#

i'll do 5

leaden ice
#

something along those lines

neon nymph
#

no i want the max jump height

leaden ice
#

Then it should not be called "jump speed"

neon nymph
#

ok

leaden ice
#

and you should make sure the calculations are such that it actually achieves that height as perfectly as possible, else it's not really an effective lever to pull on the design side.

neon nymph
#

ok but i'll try 3.5f now

vivid basin
#

can someone help me. i am building a 2 - player multiplayer game using the matchmaker service of UGS. Problem i am facing is whenever someone starts matchmaking by generating a ticket and leaves/exits the game before a match is found, the ticket generated by that player is still present in the matchmaker and gets matched to someone else even when the first player has now exited the game.

i am using the following code :

private async void OnApplicationPause(bool pause)
    {
        if (pause == true)
        {
            if (matchticketid != null)
            {
                print("pause Started");
                 await MatchmakerService.Instance.DeleteTicketAsync(matchticketid);
                  
                    print("paused");
            }
        }
        else
            print("not paused");
    }

however only "pause Started" is printed on the android logcat when game is minimised and the actual function of MatchmakerService.Instance.DeleteTicketAsync(matchticketid) and subsequent "paused" is only printed when i reopen the game.

can someone tell me how to solve this issue with the code or suggest me a different approach to my problem??

tawny elkBOT
vivid basin
rotund saffron
heady iris
#

The x/y/z/w fields on a rotation are not the euler angles

#

they're the four components of a quaternion

#

youl'l need to do something like this

#
Vector3 eulerAngles = transform.rotation.eulerAngles;
eulerAngles.x = 0;
transform.rotation.eulerAngles = eulerAngles;
rotund saffron
#

i got it ```
transform.rotation = Quaternion.Euler(0f, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);

knotty sun
#

that is not gonna work

heady iris
#

Quaternion.eulerAngles gives you a Vector3 of the euler angles. Since it's a property that returns a value type, you have to store the result in a variable, modify it, and then assign it back.

rotund saffron
#

typo with copy paste

#

thanks tho

leaden ice
hexed oak
#

Think I found a bug. I have a timeline gameobject and an animator gameobject as children to a root gameobject. Applying an animator reference to the timeline by applying the change to the root game object does not save the animator reference

bleak thorn
#

Hello, these errors appear after installing game creator asset how to fix them?

Unity version: 2022.3.14f1
Game Creator version: 1.1.16

knotty sun
bleak thorn
knotty sun
fickle sable
#

Does ExecuteInEditMode affect thhe entire class regardless of where it is placed?

#

I'm trying to have a single func execute within the editor but having the entire script run seems like a waste

knotty sun
#

I would not worry about unnecessary overhead in the Editor, Unity creates much, much more than you ever could

leaden ice
#

(executeineditmode only does something when it's placed on the class itself, IIRC)

modern creek
#

I don't do this often but I recall there is a way - how can I persist play-mode changes to editor mode? I'm tweaking some graphics on some VFX and it's a little tedious to copy and paste all the particle effect things back to the editor mode

leaden ice
leaden ice
#

and paste in edit time

#

Another cheeky way is to save the thing as a prefab at runtime

modern creek
#

hm... it didn't seem to work for particle systems - is that component actually a "surface" for all the subsystems underneath?

#

it might also be this specific component ("All In 1 Shader") that does something.. fucky with the values

leaden ice
#

Hmm really, interesting?

fickle sable
# leaden ice what are you trying to do

Just trying to toggle a scrim with specific values for testing, doing it manually has wasted far too much time. I just wanna expose a func for it via context menu.

leaden ice
#

dunno anything about this All In 1 Shader thing

modern creek
#

yeah, it's nbd for AllIn1Shader.. there's a whole bunch of custom editor stuff there.. but I couldn't seem to get the particle system "copy component values" from play mode to editor mode working

leaden ice
fickle sable
#

I'll take a look thanks 👍

modern creek
#

Hm, tried to repro it in a video and now it works. 🤷 Oh well, thanks PB.

knotty sun
modern creek
#

heh.. I'm just kidding.. most of my stuff runs pretty quickly unless I bork something up pretty bad

#

like that one time i accidentally recursively created a local material from a prefab.... oh man.. that one was bad.

#

I'm so .. timid? when it comes to accidentally fucking up an exit condition on recursion that I have widely implemented an "oops" counter

knotty sun
#

tbh the Editor is pretty easy to bork, I've just discovered an exiting new way of screwing it up with a simple spelling mistake using UI Toolkit, Oh joy

modern creek
#

I just caught up on all the patch notes while considering migrating from 2022.3.17 to 3.22 and .. it's really amazing the number of UIT fixes each release

#

i have empathy if that's your tech of choice 🙂

knotty sun
#

I just hate UI Toolkit less than I hate IMGUI

modern creek
#

really? wow.. i wish I could have a convo with you, since I've used imgui for years and every time I glance at UIT to see if I should go there.. it seems .. bad

#

I do hate very many things about imgui but .. after learning all the stupid stuff you need to do to get particles and/or shaders working.. it's functional enough

knotty sun
#

Seriously, UI Toolkit has a lot to recommend it. It's totally flexible and extendable in code which I like and it's close enough to HTML/CSS to make the learning curve shallow. I've been playing with it since it was introduced back in 2018 and I do all my Editor coding in it now.
For instance I just made this custom inspector and it took, literally, 1 hour to write

rigid island
knotty sun
rigid island
knotty sun
rigid island
modern creek
#

Question: If I wanted to make a particle system follow a custom irregular path, would NavMesh be the best solution?

unkempt monolith
#

I'm trying to attach a debugger to a build to debug an issue that only appears in standalone builds but I keep getting this error message in Rider after 20-30 seconds of waiting.

netstat shows that the player isn't even listening to the port that shows up in the attach window, even though I enabled script debugging in Build Settings

knotty sun
rigid island
#

agree, navmesh is very "stiff"

modern creek
#

Not sure what you mean. Is there a curve component of some sort?

rigid island
#

yeah unity has a Spline tool, you can also move stuff along it easily.

modern creek
#

These are irregular paths but I'd rather not create them programmatically

#

I don't see the component - is it in another package?

knotty sun
#

Sounds ike Spline is your friend

modern creek
#

thanks

#

ya this is much more what I wanted.. perfect, thanks

#

shit I wish I knew about this a while ago.. I've been moving particle attractors with tweens in a linear path (programmatically) and it's both a pain in the ass and looks a bit cavemannish

rigid island
#

to be fair I think it was only dropped in 2022?

#

yeah 0.1 came out with unity 2022.1 so whatever that is

modern creek
#

all good.. this solves so many problems I was trying to do the hard way

knotty sun
rigid island
#

it really is an amazing tool, can do all sorts of shit

modern creek
#

like I want to do these little animations of .. coins flying up into the header after a level, and i've been tweening this shit by hand

rigid island
modern creek
knotty sun
modern creek
#

OK - re splines, do they not .. work in UI space? I couldn't seem to draw a spline until I added a 3d object

rigid island
rigid island
modern creek
#

i'm digging.. it looks like maybe there's something?

But I'm not seeing any overview docs yet

rigid island
#

I think thats for editor scripting

#

iirc yeah you do need a gameobject for the Spline Container

#

which way are you trying to animate on it, it has multiple ways and a component for it too

modern creek
#

Yeah I mean, I have game objects but it looks like these don't work in UI space

#

Basically my problem is that I'd like to have some particle effects move around the border of an image

#

i tried putting the prefab into 3d mode and drawing the spline onto the object but it "missed" 😛

swift falcon
#

can u help me

unkempt monolith
swift falcon
#

!!!!!!!!!!!!!!!!!

unkempt monolith
modern creek
swift falcon
rigid island
unkempt monolith
swift falcon
modern creek
#

I suppose I could try to make a 3d object that's the size of the UI object but.. my entire app so far is in UI space so I don't know how this'll interact

rigid island
#

the whole spline is in wordspace positions

modern creek
#

ya.. it's fine, I've done worldspace-to-uispace hacky things before but it's .. kinda not fun

#

the bugs are gnarly to figure out

rigid island
#

was thinking that as well, its hacky but might just work :p

#

wonder if thats a feature request

modern creek
#

the way I'm doing my particle effects it should work - they get baked into a UI layer mesh - but it's still likely to have some position bugs/issues.. anyway, I'll see if I can get a proof of concept working and if it is reasonably functional than i'll dive in

#

what, like UI-based splines?

rigid island
#

yeah like a mode you can switch for Screen Space

modern creek
#

i don't know how unity (as a corp) feels about continued support/dev of IMGUI tbh.. it feels like there's some stagnation there

rigid island
#

and working with UGUI

rigid island
modern creek
#

yeah but UIT is something entirely different (that I don't actually have any reasonable skillset in)

#

I've kinda just always done the UGUI thing

rigid island
#

I do all my editor scripts now with UIToolkit just not in-game

modern creek
#

yeah i can't seem to get it to work.. there'd probably be an awful lot of fiddling to translate worldspace/splinespace and UI space

#

lemme clip what i did and maybe if you see any obvious mistakes lemme know

unkempt monolith
#

heh, for in-game UI I use a custom engine-independent solution -- basically UITK minus the visual trees and WYSIWYG (though that stuff is in future plans), but with less bugs and some features we specifically need that are missing in UITK (grid layouts, crisp bitmap fonts, custom widget rendering and some other things)

sadly, not gonna release it to the general public in the near future - the poor set of tooling around it and nearly completely missing docs block that

heady iris
modern creek
#

also when I set "align to world space" at the end, i got console spam with this happy message:

#

so I suspect that trying to make this work isn't going to be all that much fun/successful

#

Maybe I could use the spline programmatically like a curve? ie, just give me the location at 0<t<1

#

(and then manually move the object myself in UI space)

rigid island
#

and yeah like you said just use the spline for its shape

#

You can sample any point on the spline

modern creek
#

yeah, I think Evaluate(spline, t, position, orientation, direction) is what i want

#

i'll just send my own t in and link it to the spline and then basically treat it like a Curve variable that I can just .. use manually

#

i'm just not sure if I'm gonna need to be scaling it up/down since 3d space is so different than UI space

#

crap, I can't just link a spline in the editor.

[SerializeField] private Spline Spline;

shows this:

rigid island
#

splines need to exist inside a SplineContainer

#

so you can do SplineContainer.Spline iirc

modern creek
#

cool that worked, thanks

heady iris
#

You can grab SplineContainer.Spline to get the first spline in the container

#

which covers a lot of use-cases

modern creek
#

cool this might work!

#

(i'm just spitting out interpolated float3s along t=0-1)

#

i had to multiply the location by the scale of the 3d object but.. this could work

heady iris
#

oh yeah, a useful thing to know that's...not very obvious at first

#

SplineContainer.Evaluate works in world space

#

Spline.Evaluate gives you a local-space position

#

It makes sense because Spline is not a unity object and has no idea where its SplineContainer is

#

it's just telling you where on the spline you are at a certain t

modern creek
#

cool - well i lucked into the correct use then 🙂

heady iris
modern creek
#
        [SerializeField] private SplineContainer ParticleSplineContainer;
        private Spline _spline;
// in awake:
            _spline = ParticleSplineContainer.Spline;
            _spline.Evaluate(t, out float3 position, out _, out _);
heady iris
#

you can just use EvaluatePosition if you don't need the other two directions

modern creek
#

cool

heady iris
#

it's faster to use Evaluate than to individually calculate the position, tangent, and up vectors

#

hence why it's there

heady iris
modern creek
#

no, i want local space

heady iris
#

ah, okay

modern creek
#

i mean, i still might not be using the right hammer for this nail but.. it's a hammer

latent latch
#

oh im doing splines too right now. Trying to figure out how to make a nice arrow indicator from the UI to the world

rigid island
fluid lily
#

Hey all. I am trying to deserialize a json file, and get an array of strings from it. But when I try and cast the object to the list I am getting a conversion error.

Dictionary<string, object> assemblyData = JsonConvert.DeserializeObject<Dictionary<string, object>>(assemblyText);

List<object> crntReferences = new List<object>();
if (assemblyData.ContainsKey("references")) {
    crntReferences = (List<object>)assemblyData["references"];
}

with error
InvalidCastException: Specified cast is not valid.
Here is the json

{
    "name": "test",
    "rootNamespace": "",
    "references": [],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": [],
    "noEngineReferences": false
}
#

Was was thinking it was because it is empty, but if I put a value it still throws it. Likewise tried object[] instead of list, but no luck

knotty sun
fluid lily
#

How would I get the values from it then? When I am serializing it back to json I just use a list<string>, and that works.

#

Or are you just talking about the
Dictionary<string, object>
which yes, but is just holding the data

knotty sun
#

I'm talking about your json, that is an object, so you will need a C# class that mirrors it's structure

fluid lily
#

yeah,,, which the dictionary is doing

knotty sun
#

no, a dictionaty is an object which contains an array of key value pairs

fluid lily
low owl
#

anybody successfully point elbows/arms in an Animator using OnAnimatorIK()?

Im trying to point my elbow in the direction of where im looking for a flashlight. It seems like it should be easy but that has not been the case.

shrewd mulch
#

what is it called when you start typing something in vs code and then a pop up shows and it is like a search bar

fluid lily
heady iris
rigid island
low owl
shrewd mulch
#

let me search Code suggestion

rigid island
# low owl oh fr?

Intellisense is showing you the recommended suggestions based on what you typed

heady iris
#

The problem is that there's no coherent way for it to pick types

shrewd mulch
#

but i found it

knotty sun
heady iris
#

What should the type of the value associated with references be?

#

You must tell it exactly how to interpret this data.

#

Create a class whose structure matches the data.

fluid lily
knotty sun
fluid lily
low owl
heady iris
rigid island
fluid lily
heady iris
#

Do you expect it to sometimes emit a List<object> and sometimes emit a List<string>?

#

How does it know that a string isn't actually an encoding of some other type that it's supposed to be deserializing to?

rigid island
fluid lily
#

Reflection, Dynamics, many tricks. but in this case it just lazy deserialized to a string, which is fine and all I needed to know.

heady iris
fluid lily
heady iris
fluid lily
#

Look it up

heady iris
# fluid lily I am infact not

Reflection is wholly irrelevant here, given that it's introspection of C# objects, not analysis of serialized data

main pawn
heady iris
#

(beyond the use of reflection to actually produce arbitrary types whilst deserializing, of course)

fluid lily
#

one of the ways

heady iris
fluid lily
#

Actually I have my answer from me, y'all tried to answer a question I didn't ask, and then condescend to me

knotty sun
#

oh, dear, 'A little knowledge is a dangerous thing'

fluid lily
main pawn
#

Hey, anyone know about the tween thing> Or is this a bad time?

latent latch
#

You iterate by kvp if you want to foreach the dictionary if that's your problem

heady iris
#

There are a lot of third-party tweening libraries

rigid island
main pawn
heady iris
#

I haven't used any myself

#

because i'm like that, mostly

#

i should really try one out

main pawn
rigid island
main pawn
#

Half my game, and all of my UI runs on it

main pawn
latent latch
#

one day ill look into tweening but lerping seems to be carrying me far

main pawn
#

Or just meshRenderer[i].materials[0].DOColor(Color.clear, 0.5f);

#

Tried both

heady iris
#

Does directly setting the color to Color.clear work?

rigid island
heady iris
#

If not, perhaps your material is opaque/doesn't have alpha clip enabled.

modern creek
main pawn
heady iris
heady iris
#

you're going to need to provide much more information here

rigid island
main pawn
#

Not just a colour

heady iris
#

that's very standard

#

you can still set the tint color on most shaders

main pawn
#

Right.

modern creek
main pawn
#

meshRenderer[i].materials[0].color = Color.clear; didn't work either

modern creek
#

I have to clean up the code a lot, since there was a lot of fiddling, but basically:

            float3 position = _spline.EvaluatePosition(t) * _cubeScale;
            (GoldParticles.transform as RectTransform).anchoredPosition = new(position.x - XOffset, position.y - YOffset);
rigid island
#

cool glad to know that works without extra fiddle

modern creek
#

i'm still not quite sure why I had to offset the things (with the X and Y offset there) since it .. came out oddly positioned? but it's working well enough that I'll probably use it again

#

after like 30 minutes of trying to figure out why, I gave up and just duct taped it with those offsets :p

rigid island
#

haha yeah I recall having to deal with using the SplineUtility to do some conversion for getting my player to grind on it

heady iris
heady iris
#

also, show us the material being used on the renderer

main pawn
#

I can try it on a cube tho

heady iris
#

the inspector for the material, I mean

#

I'm not familiar with that shader.

main pawn
heady iris
#

turn on "Cutout Transparency"

main pawn
heady iris
#

if the material is opaque, then alpha will be ignored unless you're using cutout transparency (which i'd call alpha clip)

main pawn
heady iris
#

alpha clip means each pixel either draws or doesn't draw

#

there's no in-between

#

You need a transparent shader.

#

There might be a separate transparent shader to pick

main pawn
#

It does do transparancy, kinda, but I'm not sure how

heady iris
#

the OmniShade page suggests there's a transparent version

main pawn
#

There is one, yeah. Would that help?

heady iris
#

A transparent shader can blend with whatever is behind it, so lerping the color to Color.clear will make it smoothly disappear

main pawn
#

Ah okay

#

Does seem to work on the material itself, though the tween not so much

#

Would doing this affect only those objects, or every wall?

heady iris
#

When you access the material or materials property of a Renderer, it creates a unique copy of the material if one hasn't been made already

heady iris
#

sharedMaterial doesn't do this, so you'll wind up modifying a material that many things use (and modifying your assets, too)

twilit scaffold
#

Ok, i am on my adventure to actually learn and understand C#, instead of battling each problem as i get to it. I am at the point of learning how to handle exceptions. When i hover over most things, it clearly shows what exceptions may occur, so i can handle them.
But, there is a divide by zero exception that is not listed in any hover. Granted, as a concept it is global, but it seems it should still be listed under the / operator, at least. i am using Visual Studio

knotty sun
#
try {
//Code Here
} 
catch (Exception ex) {
   Debug.Log(ex.Message);
   Debug.Log(ex.StackTrace);
}

is a good place to start

fallow obsidian
#

I was trying to use the <mspace> rich text tag with TextMeshPro and it looks like that's only available in TextMeshPro 4.0. Unity's Package Manager doesnt give me an option to update to that version so im guessing this version may be specific to a unity editor version. Anyone have any clue what unity version I'd need for this? :O

plucky inlet
gray mural
#

Hello, according to JoshPeterson on this thread, using dynamic keyword in Unity won't work out well.
Any thoughts on how I can subtract 2 T type fields without using it?

public T min;
public T max;

public T Diff => (dynamic)max - (dynamic)min;
heady iris
#

alas, we don't have the numeric interfaces yet

#

I just wound up writing separate methods for each concrete type

gray mural
#

oh, this might be strange to write for every single type

fallow obsidian
heady iris
#

I've used dynamic before for some very evil stuff involving enums and a generic type parameter

#

I know that it doesn't work with IL2CPP

#

(because that requires ahead-of-time compilation!)

gray mural
#

I see, guess I'll just subtract the fields manually

fallow obsidian
#

hmm yea i still dont see version 4.0 with Pre-release packages ticked

leaden ice
fallow obsidian
#

(can see the other pre release package in there)

gray mural
plucky inlet
#

Unity version

fallow obsidian
#

2021.3

plucky inlet
#

yeah, its 2022 minimum

gray mural
fallow obsidian
plucky inlet
fallow obsidian
plucky inlet
heady iris
#

it's annoying

plucky inlet
#

select 3.x and open the dropdown, it will show 4.0

#

yep, bad ux design, but now you know 😉

fallow obsidian
#

or.. it doesnt

#

bad choice of words

dim mica
#

Hey i just need a bit of help here :

#
ImageGO.GetComponent<Image>().sprite= Resources.Load <Sprite>(CurrentEvent.EventImgPath);
        Debug.Log(CurrentEvent.EventImgPath);
#

it returns my Path that i directly copied from "copy path" on the image i want, but my sprite is still blank ?

twilit scaffold
knotty sun
dim mica
knotty sun
#

ok, read the docs posted by @somber nacelle

dim mica
#

Oh i need to replace Sprites by Ressources ? like it said here :
//Load a Sprite (Assets/Resources/Sprites/sprite01.png)

heady iris
#

You need to read the documentation.

#

That is still very wrong.

plucky inlet
#

Your sprites subfolder needs to be inside Resources to be able to load from Resources.Load

heady iris
#

The documentation fully explains what to do.

fallow obsidian
#

hmm this is strange, even after switching the project to open with 2022.3, TMP 4.0 wont show up in package manager Hmm

plucky inlet
#

try importing manually via name and version com.unity.textmeshpro@4.0

dim mica
#

like this ? cuz it don't work

heady iris
fallow obsidian
#

tried, the ui goes gray for a bit and then returns to normal but doesnt install the package Hmm

heady iris
#

It explains the path you need to pass to Resources.Load.

heady iris
plucky inlet
dim mica
#

(i'm not english it's a bit hard to understand everything)

heady iris
dim mica
#

oh ok just saw it

still carbon
#

I was looking into why some of the trees in Gaia have a harsh light/dark transition between LODs and saw something I wasn't expecting. I thought that Unity just hard-transitioned between LODs but it looks like it's a bit smarter - like it gradually adds or removes shadowing from the about-to-be-added-or-removed geometry. Is that correct? If this is done via Unity, Is there a way to control that transition - increase the "LOD shadow overlap" range? The problem is that if you're moving at anything other than a very slow rate of speed the shadow transition happens in a split second, thus negating the benefit of this cool feature.

heady iris
#

(and it does not include any file extension)

dim mica
#

thx it works now !

plucky inlet
fallow obsidian
#

wonder if there's a git url i could try from

plucky inlet
#

[4.0.0-pre.2] - 2021-11-20 , last update on that package

#

[3.2.0-pre.9] - 2024-02-20

fallow obsidian
#

that's depressing... Now i gotta find an actual monospaced font wah

#

oh wait maybe there is mspace in 3.2.0

plucky inlet
fallow obsidian
#

except i cant seem to install that either 😂

plucky inlet
#

you sure, its not working with the one you can install, i assume 3.0.8?

fallow obsidian
#

yea mspace isnt a thing in 3.0.8

heady iris
#

Is that enabled?

fallow obsidian
fallow obsidian
#

hmm one sec

#

ooh it does work
i think i only tested with an even older version lol

#

thanks

plucky inlet
rotund saffron
#

i cant get the forearm to point at aim object here, spine works fine , forearm is always twisted ~180 degrees away, tried nearly every aim axis and up axis combo

half cosmos
#

Quick question,how do I prevent a tilemap from disappearing whenever its layer is changed from default -> literally anything else

heady iris
#

sounds like you've got your camera's culling mask set to only render the Default layer

half cosmos
#

im trying to assign it a separate layer in order to detect collision for specifically that tile map

#

ah ok

heady iris
#

check the inspector for your camera

half cosmos
#

Would that affect it even when outside of play mode?

heady iris
#

Yes, but only if you're looking at the game view

#

If it's vanishing from the scene view, then that could be caused by...

#

the Layers settings up in the top right corner

half cosmos
#

Yeah imlooking at scene view

#

ok lemme check

#

yup thats exactly the issue tysm

heady iris
#

no prob (:

half cosmos
#

lol

#

ugh now I need to figure out how to actually detect the collision

heady iris
#

a tilemap collider component on the same object as the tilemap will work

#

that'll give you a collider you can bump into, at least

half cosmos
#

Basically, I just want an event to trigger whenever the player sprite walks over a certain tilemap

#

thats basically it

#

player should still be able to walk over it

heady iris
#

it works just like any other 2D collider, so you can respond to collision or trigger messages

half cosmos
#

thing is, I have no idea what to write to acc check for the collision notlikethis

#

Im tryna look it up atm but no luck

heady iris
#

if you want to respond to a collision

half cosmos
#

thanks

misty blade
#

can I use JSON or XML to store game data instead of scriptable objects? I feel like thats much more manageable in larger projects. If yes are there any tutorials or docs on it?

rigid island
#

I use both though SO +Json

heady iris
half cosmos
heady iris
#

The nice thing about using a scriptable object is that it can directly reference other assets.

misty blade
# rigid island I use both though SO +Json

what about referencing files like sounds (.wav for example) or textures? Let's say I have a sound class with some properties like the audio clip, volume etc. If I wanted to load sounds data from json how could an audio clip be referenced?

lean sail
#

If you need it to reference something else, then SO is definitely easier here

lean sail
#

Otherwise you gotta serialize some ID and match that ID to the item when parsed

heady iris
#

you don't reference a .wav

misty blade
heady iris
#

you reference an AudioClip that's imported from a .wav file by the unity editor

#

If you want to be able to point to an arbitrary .wav file on the player's computer at runtime, you need to read the file and turn it into an AudioClip yourself.

#

(This is pretty easy, mind you, but I'm pointing out that it's not at all like just referencing other assets from a ScriptableObject asset)

misty blade
#

could I build my own folder structure for that maybe? Like an external folder with .wav files that json could reference

lean sail
# misty blade it feels great for moddability too

In what sense? You edit a file vs edit fields on the inspector. If your file gets large, that's gonna be worse to search through. If you split up the file into many files, it's the same as using SO except without having access to use editor functionality with it

misty blade
#

I meant for mod support. I don't see how externally you could add your own SO's (but maybe I lack knowladge in this area), but if you store data in you project build folders then you could just easily add more content

lean sail
#

Json does not reference anything, keep that in mind, it is simply text. You may store an ID or folder path in there, but either one of those simply match an existing ID or path that must be looked up. If either ID or path is deleted, you now have an error because it's not automatically referenced

half cosmos
#

@heady iris I tried this but nothinghappens

heady iris
heady iris
#

notably, including adding some log messages to check if the method is running at all

misty blade
heady iris
#

I've set things up so that I could rename all of my settings and existing save data would still work perfectly fine

half cosmos
#

I've tried debugging through that but it hasn't helped either @heady iris

#

I don't think there's anything wrong with what I've used

heady iris
#

tell me the things you've checked, then

half cosmos
#

It's asked if both have a collider 2D, which they do

#

pretty sure they match in the trigger matrix as well

#

Its not inside of another function either

heady iris
#

is at least one of them a trigger collider?

half cosmos
#

yeah

heady iris
#

and does at least one have a Rigidbody2D on it?

half cosmos
#

I have a composite and tilemap collider 2d on the tilemap the player is walking over

#

yeah the player and tilemap both have rigidbody 2d

#

Wait is it an issue if both rigidbody2d are set to static?

heady iris
#

I'd expect so, yes

#

Consider making the player kinematic

half cosmos
#

but its a 2D game I need them to stay on the map

heady iris
#

a kinematic rigidbody isn't pushed around

half cosmos
#

oh mb

#

yh thats dynamic LOL

dense lark
#
void OnDefend() {
        if (defend) { 
            defensiveCamera = Instantiate(defensiveCameraPrefab);
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        } else {
            Destroy(defensiveCamera);

            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
           
        }
    }```
if I press a button, create a new camera. if i press it again, delete the camera. why is it not deleting the camera?
half cosmos
#

private void OnTriggerEnter(Collider other)
{

 int num = Random.Range(0, 101);
 if (other.tag == "Player")
 {
     if (num > 10)
     {
         Debug.Log("Triggering Random battle");

     }
 }

}

#

this is what im using

heady iris
heady iris
dense lark
#

yes

heady iris
half cosmos
heady iris
#

but the game object (and all other components) will survive

#

you could destroy defensiveCamera.gameObject to get the entire object

#

also, that's not a cinemachine camera, right?

dense lark
#

no

heady iris
#

if so, that means you are now rendering two cameras simultaneously

dense lark
#

also the camera script is attached to my player

#

so destroying gameobject would destroy my player

half cosmos
#

IT TRIGGERED

heady iris
#

It just instantiates a prefab.

heady iris
dense lark
#

wait

heady iris
#

gameObject is this.gameObject, which is the object your component is attached to

dense lark
#

would that not be my player?

heady iris
#

gameObject would be the player's game object if this component was attached to the player, yes

#

but defensiveCamera.gameObject would be the object that defensiveCamera is attached to

#

which is probably not the player, yes?

dense lark
#

wait

dense lark
heady iris
dense lark
#

this is the defense camera

heady iris
#

!code

tawny elkBOT
dense lark
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DefendMenu : MonoBehaviour
{
    public bool defend = false;
    public GameObject defensiveCameraPrefab;

    [Range(1f, 20f)]
    public int speed;

    private GameObject defensiveCamera;

    void Update() { // Update is used here to check for the 'F' key press
        if (Input.GetKeyDown(KeyCode.F)) {
            defend = !defend;
            OnDefend(); 
        }
    }

    void OnDefend() {
        if (defend) { 
            defensiveCamera = Instantiate(defensiveCameraPrefab);
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        } else {
            Destroy(defensiveCamera.gameObject);

            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
           
        }
    }
}```
heady iris
#

ah, that'll do (:

#

Okay, so defensiveCameraPrefab is not a Camera

#

It's a GameObject.

#

public GameObject defensiveCameraPrefab;

dense lark
#

my bad

heady iris
#

defensiveCamera is also a GameObject

#

If they were both Camera variables, then you'd need to grab the gameObject property from them to destroy the entire object

#

But they're GameObject variables, so you already have the game object

#

This looks fine to me.

#

Did you get an error in the console?

dense lark
#

it just doesn't delete the camera

heady iris
#

does a new camera spawn every time you hit F?

dense lark
#

yes

heady iris
#

or is it every second time?

dense lark
#

or no

#

every second time

#

the defense bool gets switched each time F is pressed

heady iris
#

show me a screenshot of your entire console

#

making sure you don't have errors hidden

dense lark
#

one second

heady iris
#

okay, good, no errors

#

these buttons would be colored darker if you had info/warning/error messages hidden

dense lark
#

i see

heady iris
# dense lark

Perhaps you have more than one thing spawning defense cameras? Try logging at the very start of OnDefend.

#

although, if you had duplicate defend menus, each one would still be cleaning up after itself

dense lark
#

what do i log?

heady iris
#
Debug.Log("Defend called", this);
#

that'd let you click on the log entry to see who logged it

#

But if only one camera is appearing at a time, then I doubt you have duplicates.

dense lark
#

yk what

heady iris
#

Does anything else set the defend field on DefendMenu?

dense lark
#

is it possible to just create an instance of the defense camera in my scene, have it disabled, and then just turn it on/off when I press F?

heady iris
#

I noticed you have a UI button that does it

#

I wonder if something else is interfering

dense lark
heady iris
#
[SerializeField] Camera defenseCamera;
#

(this way, it's not public, so other classes can't mess with it)

dense lark
#

okay

heady iris
#

and since it's a Camera, not a GameObject, you can just enable / disable the camera

#

instead of having to deactivate the game object or use GetComponent on it

dense lark
#

and how would i go about turning it on/off?

#

is there a method that lets me do that

heady iris
#

many things have an enabled property

dense lark
#

so camera.enabled = false should do the job im assuming

heady iris
#

Correct.

dense lark
#

tysm

#

works now

heady iris
#

The only avenue I see is for something to have been messing with defend, since it's public

dense lark
#

idk, i was probably stuck trying things for an hour

languid hound
#

Oddly specific but I cant really find much. I'm trying to find the corresponding sharedmesh that a raycast hit. This will be running on android (specifically quest 2) so I want to make this as performant as possible. Is there any better way of doing this?

                MeshFilter filter = hitInfo.collider.GetComponent<MeshFilter>();
                MeshRenderer renderer = hitInfo.collider.GetComponent<MeshRenderer>();

                if (renderer != null && filter != null)
                {
                    for (int i = 0; i < filter.sharedMesh.subMeshCount; i++)
                    {
                        int[] indicies = filter.sharedMesh.GetIndices(i);
                        
                        for (int x = 0; x < indicies.Length; x++)
                        {
                            if (x == hitInfo.triangleIndex)
                            {
                                Debug.Log(renderer.sharedMaterials[i]);
                            }
                        }
                    }
                }
#

It just feels a wee bit off

#

Not very experienced with any mesh related things so I've probably gone down some unnecessarily unperformant route

#

In-fact this doesn't even work annoyingly.. any other suggestions?

#

Thought it did until I threw more materials into the mix

delicate granite
#

hey, i made (followed a youtube tutorial) a car controller script thing. it works until i try making the wheels visuals work.
the part of the script used is

void FixedUpdate{
// the rest of the script that makes stuff work
 UpdateWheel(frontLeft, frontLeftTrans);
        UpdateWheel(frontRight, frontRightTrans);
       UpdateWheel(backLeft, backLeftTrans);
        UpdateWheel(backRight, backRightTrans);

    }

void UpdateWheel(WheelCollider col, Transform trans) {
        Vector3 pos;
        Quaternion rot;
        col.GetWorldPose(out pos, out rot);
        trans.position = pos;
        trans.rotation = rot;
    }

the car flips horribly when the wheel turning part is added. does anyone know why it does this?

thanks!

half cosmos
#

what's the equivalent of using "yield return new WaitForSeconds" in a public void?

#

I want to add a bit of a delay in the function

delicate granite
#

starting a coroutine and then making it go back i think

#

idk im not the best at this

quaint rock
#

is none

spring creek
#

Yielding to the main thread requires an asyncrounous function, which a coroutine is

#

The IEnumerator it returns is HOW it can yield (it enumerates the state of the coroutine)

heady iris
#

I wouldn't say you're "yielding to the main thread"

#

yield statements in an IEnumerator-returning method cause the enumerator to pause until it's resumed by a MoveNext() call

quaint rock
#

yeah coroutines have nothing to do with multithreading

heady iris
#

You can't do this in a function that's not being used as a coroutine.

quaint rock
#

its jsut yielding till a future frame

heady iris
#

Waiting for one second in an Update method would freeze the game for one second.

heady iris
spring creek
#

Yeah sorry that was not clear. I know it has nothing to do with multithreading. I just meant it yields, allowing other code to run. Which is this case is stuff on the main thread since coroutines are not multi-threading

heady iris
#

also, hitInfo.triangleIndex is a triangle, not a vertex

#

oooh, no, GetIndices gives you an array of vertex indices used in triangles

#

so that's reasonable

#

but your code isn't actually checking against those indices right now

for (int x = 0; x < indicies.Length; x++)
{
    if (indices[x] == hitInfo.triangleIndex)
    {
        Debug.Log(renderer.sharedMaterials[i]);
    }
}

it ought to look like that

#

...well, no, that's still wrong

#

hitInfo.triangleIndex isn't a vertex index; it's a triangle index

heady iris
#

public is a member access modifier, which controls who is allowed to see the method

#

and void is the return type of the method

#

the method returns nothing, so the return type is void

heady iris
#

i.e. if submesh 0 has triangles 0 through n, submesh 1 has triangles n+1 through n+m, etc.

half cosmos
lavish laurel
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCombat : MonoBehaviour
{
    private Animator anim; 
    //Unity Accessable Variables
    [SerializeField] private GameObject attackPoint; 
    [SerializeField] private float attackRange = 0.5f; 
    [SerializeField] private float damage; 
    [SerializeField] private LayerMask enemyLayers; 
    [Header("Attack Sound")]
    [SerializeField] private AudioClip playerSwordSound;

    private void Awake()
    {
        anim = GetComponent<Animator>();
    }

    private void Update()
    {                              
        if (Input.GetMouseButtonDown(0)) //check if left mouse button is pressed
        {
            anim.SetBool("isAttacking", true); //check is boolean is true
        }

    }

    public void Attack() //call attack funtion
    {
        SoundManager.instance.PlaySound(playerSwordSound);
        anim.SetTrigger("attack"); //play animation

        Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.transform.position, attackRange, enemyLayers); //creates circle from point and collects objects that comes in contact with it


        foreach(Collider2D enemy in hitEnemies) //damage enemies 
        {
            Debug.Log("We hit " + enemy.name);
            enemy.GetComponent<EnemyHealth>().health -= damage; //enemy health becomes equal to damage that's been dealt
        }
    }

    public void endAttack() //funtion called at the end of the attack animation
    {
        anim.SetBool("isAttacking", false); //check if we can swap animations (is attack done or not)
    }

    public void Destroy()
    {
        anim.SetBool("destroy", true);
    }

    private void OnDrawGizmosSelected() //Grab ability to draw attack sphere
    {
        if (attackPoint == null)
            return;

        Gizmos.DrawWireSphere(attackPoint.transform.position, attackRange); //draw attack sphere 
    }
}
#

Does anyone know why when I spam my mousebutton is locks the attack on last animation frame but works fine when I simply click?
Also when it locks it recontines the attack upon landing

lethal vigil
#

how can i stop the Bee from looking so blurry?

quartz folio
spring creek
lavish laurel
spring creek
#

Turn on interpolation on the rigidbody

lethal vigil
spring creek
#

Show code since you're in a code channel

lethal vigil
#

sure, this is the code of my bee ```using System.Collections;
using UnityEngine;

public class EnemyAutoMove : MonoBehaviour
{
private Rigidbody rb;
public int enemySpeed = 14;
private float amplitude;
private float frequency;

void Start()
{
    rb = GetComponent<Rigidbody>();

}

void FixedUpdate()
{

// Calculate the target velocity
Vector3 targetVelocity = new Vector3(-enemySpeed, 0, 0);

// Assign the target velocity directly to the rigidbody
rb.velocity = targetVelocity;

}

}

lavish laurel
spring creek
#

Wait, IS the bee blurry?

#

Looks just low pixel count to me maybe with some anti-aliasing

lethal vigil
spring creek
lavish laurel
#

low quality does mean blurry

lethal vigil
spring creek
heady iris
spring creek
#

Profile things to see if there is an issue

lethal vigil
gloomy rover
#

Hi I am using a characterController.isGrounded to check if the character is grounded, but sometimes when I try to jump mid air when the character lands sometimes it stops mid air and then instantly jumps instead of falling to the ground.
Here is a snippet of the code:

rigid island
lavish laurel
gloomy rover
#

I am struggling with this basic problem im kinda new

full canopy
#

I'm finishing up the movement system for my vr game and one of the last things I want to add is the ability to climb/vault over objects. I don't want the player to be able to scale any wall, but I do want the player to be able to climb up any object if they can grab the upper outer edge of it. The player's hand colliders are triggers for other reasons.
Basically, I want them to be able to climb if they grab anywhere on the green, and not inside the object or anywhere in red.
I have tried several methods and they either involve tediously adding thin horizontal capsule colliders to the top edge of each object in the scene (even worse on curved objects), or would be extremely unreliable in use. I don't know where to go from here so I would appreciate any advice i can get

heady iris
full canopy
#

i thought of that but don't know how to account for only finding the edges

heady iris
#

I was prototyping a parkour game a few months ago (didn't get very far into it)

#

oh hey, I can just look at the code i wrote for that

full canopy
#

somehow i've not had that happen to me once while working on this lol

heady iris
#

this is...not very enlightening, is it

full canopy
#

nope lmao

heady iris
#

This was for vaulting up onto a surface

#

so it's actually more complex than what you need anyway

full canopy
#

well no id need the ability to do both

#

climbing over and climbing onto

heady iris
#

I'd shoot a single ray down from the player's hand to find the surface

#

Next, I would shoot many rays downwards along a line between the player's head and the player's hand

#

the rays would have a length a bit longer than the distance from the hand to the surface

#

If too many of those rays hit a surface, then the player's hand isn't on an edge

full canopy
#

ah that makes sense

heady iris
#

note that this doesn't do anything if the point is inside the collider

#

hmm, although i'm not sure exactly how that'd go

heady iris
# heady iris this is...not very enlightening, is it

This system fired a bunch of raycasts forwards. If one hit the surface and the next one didn't, then the edge must be between those two rays.

Then it shot rays inwards from your left and right shoulders to find places to put your left and right hands

full canopy
#

well i dont have to worry about moving the hands given this is vr

heady iris
full canopy
#

i think ive got the idea enough to get something similar working, thank you!

heady iris
#

Firing many rays did work pretty well for finding an edge

full canopy
#

thats pretty smooth

heady iris
#

it might have trouble on more complex colliders

lofty crest
#

how do i change the default blend in cinemachine?

#

using code

lofty crest
spring creek
#

You can of course ask about code in that channel. In case you weren't sure

low acorn
#

Can someone give me an example of how i would use "GetNearestPoint<T>(...)" from SplineUtility ?
I feel like I can almost understand the documentation but I definitely need to see an example on how to set it up.

low acorn
#

Its a method which i dont think ive used before in c# so hopefully i just dont understand how to set up methods.

cosmic rain
low acorn
#

I cant even get my editor to understand what im writing. Havent even tried actually plugging in an actual spline, give me a sec ill paste my code

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Splines;
using Unity.Mathematics;

public class AiControls : MonoBehaviour
{
public SplineContainer spline;
public float3 start;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    GetNearestPoint
}
public static class SplineUtility
{
    public static float GetNearestPoint<T>(T spline, float3 point, out float3 nearest, out float t, int resolution = 4, int iterations = 2) where T : ISpline
    {
        nearest = point;
        t = 0;
        return
    }
    
}

}

somber nacelle
#

you're not meant to try and recreate the method in your own code. you call SplineUtility.GetNearestPoint

#

also !code 👇

tawny elkBOT
low acorn
#

Ah i forgot the paste code command thx

#

And ofc its something stupid simple smh

#

Thanks so much

cosmic rain
low acorn
gentle glen
#

Hello fellow Unity devs, I re-encountered the problem I had with the WorldToScreenpoint function.
As you can see in the screenshot, the target lock icon is at the bottom left. It is supposed to be where the X is marked.

ocean hollow
dusk apex
#

If the ui is offset by some parent container, apply the position change to the localPosition property rather than position.

gentle glen
#

However it also doesn't work

#

Sorry for the bad explanation, it hides when it is not locked on

ocean hollow
ocean hollow
gentle glen
#

just a simple inactive

dusk apex
dusk apex
gentle glen
#

but it's not a parent to anything

dusk apex
#

Where do you apply enemyPos to the position of the ui?

gentle glen
dusk apex
gentle glen
dusk apex
#

That's where you've assigned it. Where do you apply it to the ui transform?

dusk apex
#

Where in code?

gentle glen
#

lockOnGraphic.position = enemyPos;

#

Despite usiung a test transform, the lockOnGraphic still appears in the same bottom left area

dusk apex
#

Alright, so maybe you ought to call DefSetup after updating the position?

gentle glen
#

It's meant to really be called in Update()

dusk apex
gentle glen
dusk apex
#

Else the value isn't updated to the current enemy position

gentle glen
#

oohhhh i see what you meant

gentle glen
# dusk apex

I applied this to my script, and it still didn't work

#

I tried using a different image and it still returned the same behavior

dusk apex
#

Can you show the updated script?

gentle glen
#

I'm only gonna show void Update for now

#
void Update()
    {
        tgtI = bbRikusen.targetIndex;
        if(tgtList.Targets[tgtI].tag.Equals("GiodEBody") == true)
        {
            unitMN.SetText("GD-03");
            apMeter.maxValue = tgtList.Targets[tgtI].GetComponent<GiodEAPH>().MAP;
            apMeter.value = tgtList.Targets[tgtI].GetComponent<GiodEAPH>().CAP;
        }

        if(tgtList.Targets[tgtI].tag.Equals("EnemyTurret") == true)
        {
            unitMN.SetText("TURRET");
            apMeter.maxValue = tgtList.Targets[tgtI].GetComponent<EnemyTurretAPH>().CAP;
            apMeter.value = tgtList.Targets[tgtI].GetComponent<EnemyTurretAPH>().AP;
        }
        lockOnGraphicGO.SetActive(LockedOn);
        tgtListTransform.RemoveAll(s => s == null);
        enemyPos = Camera.main.WorldToScreenPoint(tgtListTransform[tgtI].transform.position);
        DefSetup();
    }

    public void DefSetup()
    {
        tgtI = bbRikusen.targetIndex;
        lockOnGraphic.position = enemyPos;
        tgtI = bbRikusen.targetIndex;
        LockedOn = bbRikusen.LockAtTarget;
    }
dusk apex
#

Try placing this before the DefSetup linecs Debug.Log($"{tgtListTransform[tgtI].name} was targeted at world position {tgtListTransform[tgtI].transform.position} and at the screen position {Camera.main.WorldToScreenPoint(tgtListTransform[tgtI].transform.position)}", this);Edited typo

gentle glen
#

Alright

#

Gonna send the debugs after playtesting

quartz folio
#

God I wish people would use the debugger

gentle glen
#

Turret was targeted at world position (376.00, 50.84, 70.60) and at the screen position (960.00, 540.00, 211.79), this
UnityEngine.Debug:Log (object)
BloxBotLockOnFunction:Update () (at Assets/Scripts/Units/EOT/Blox Bot/HUDControl/BloxBotLockOnFunction.cs:55)
Screenshot:

gentle glen
quartz folio
#

It seems very weird to set something's world position to a screen position

#

Also worth noting that UI space is not necessarily screen space. If this uses UGUI then you would need to account for UI scaling

dusk apex
#

I've got to go, good luck

gentle glen
spring creek
tawny elkBOT
spring creek
#

As it is, I would have to download a file to look at it
(I'm on mobile)

gentle glen
gentle glen
#

is it ok if you can help me
i tried help from other people
and it seems like i can't get it through
no matter what i do

#

oh wait
looks like i found a solution
it really has to be a separate GO canvas with world space

fleet gorge
#

right now I'm looking to render the vfx for a player when the sword is swung; is it more common for a whole gameobject to be created with a mesh renderer? or is it just fine to use Graphics.RenderMesh?

Because when I think about it I still find myself changing the localposition of the gameobject and raycasting, and not needing the functionality of the gameobject.

#

Is there a better way to do this than call graphics rendermesh every frame? Or is that how the mesh renderer itself does it

west lotus
#

In the most basic case yes a meshrenderer would result in a draw call similar to Graphics.RenderMesh

cosmic rain
west lotus
#

But if your vfx is a mesh, why not just enable/disable the GameObject? I feel like manually drawing the mesh adds unnecessary complexity to this.

fleet gorge
#

Frankly I don't like having too much referencing to other gameobjects in the scene, so I keep as much behaviour of the script to one gameobject if possible