#archived-code-general

1 messages Β· Page 271 of 1

hexed pecan
#

Have you confirmed that your ground check works while going down a slope?

#

Like does it return true

heady iris
#

I'm guessing you have a problem somewhere else. Maybe your ground check is wrong. Maybe vel is already compensated partially for your orientation and now you're double-correcting it here

hexed pecan
#

I can't pinpoint the problem but I assume it has to do with verticalMove + groundedness

heady iris
#

if vel has already been rotated, rotating it again will give you a vector that points partially into the floor

dense estuary
heady iris
#

in that case, you'd need to use Quaternion.FromToRotation(transform.up, slopeHit.normal)

#

rather than rotating from world +Y

#

you can use Debug.DrawRay to visualize what's going on here

hexed pecan
#

@heady iris video here

#

Character seems to be pointing up

dense estuary
hexed pecan
#

You mean X rotation

heady iris
#

oh, one important thing...

hexed pecan
#

Y rotation is side to side

heady iris
#

you should rotate the desired move vector, not the player's actual velocity

#

You're rotating your actual velocity

#

so if you're already moving down the slope, this tries to rotate your velocity vector 45 degrees into the ground

#

which slows you down significantly

hexed pecan
#

Good catch

heady iris
#

I've implemented this exact thing more than a few times πŸ˜›

dense estuary
hexed pecan
heady iris
#

Correct.

dense estuary
#

instead of this?

heady iris
#

You want to adjust the intended movement

#

imagine you're already sliding down a slope

#

and you aren't trying to move

#

you shouldn't mess with the player's velocity at all

dense estuary
heady iris
#

The short arrow is the player's velocity. The long arrow is the velocity after running it through SlopeVelocityChange

heady iris
dense estuary
heady iris
#

Show me your new code.

dense estuary
heady iris
#

verticalMove needs to come out desiredVelocity.

#

that's not part of your actual move input

#

Break your original velocity into two pieces:

  • the part that's aligned with the plane of the slope
  • the part that's aligned with the normal of the slope

Use Vector3.MoveTowards to move the first part towards the desired velocity (which is constructed only from your move input).

Put the two pieces back together.

#

You'll need to know the slope normal to do that

#
Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeNormal);
Vector3 normalVelocity = Vector3.Project(velocity, slopeNormal);

planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);

velocity = planeVelocity + normalVelocity;
#

This gets around a major problem with the code:

        velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
        velocity.y = verticalMove;
        velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
#

This doesn't let you accelerate in the world Y axis

#

which means you're accelerating slower on slopes

dense estuary
heady iris
#

This doesn't rotate the velocity vector.

dense estuary
#

Is that supposed to go in the SlopeVelocityChange?

heady iris
#

I left out the part where you calculate and correct desiredVelocity

#
        Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
        desiredVelocity = SlopeVelocityChange(desiredVelocity);
heady iris
dense estuary
#

The player just went up a ramp super quick and back down super slow?

#

Here's what I got:

void PlayerMove()
{
    Vector2 moveValue = move.ReadValue<Vector2>();

    Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
    desiredVelocity = SlopeVelocityChange(desiredVelocity);

    Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeHit.normal);
    Vector3 normalVelocity = Vector3.Project(velocity, slopeHit.normal);

    planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);

    velocity = planeVelocity + normalVelocity;

    Debug.Log(desiredVelocity);

    controller.Move(velocity * Time.deltaTime);
}```
heady iris
#

doesn't your SlopeVelocityChange method check the sign of y?

#
            if (adjustVel.y < 0)
            {
                return adjustVel;
            }
#

yeah

#

so it's going to behave differently going up and down slopes

#

ah, and one other thing

dense estuary
#

Okay, well that fixed that problem, but now there is another. There is no gravity, I am just sticking to the ground.

heady iris
#

verticalMove isn't being included

#

Just add gravity at the end. You don't really want to keep track of the vertical move separately

#

since your movement can now go in the +Y/-Y direction

#

A separate verticalMove made sense when your movement was strictly in the XZ plane

#

You will probably want to use controller.velocity to figure out how fast you actually moved

#

Alternatively, you can set normalVelocity to zero if it's pointing into the ground and you're grounded

#

That's a good fit for how verticalMove used to work

#

so verticalMove (which could only be in the Y direction) is replaced by normalVelocity (which can point in any direction)

#

on flat ground, they're exactly equivalent

heady iris
#

The big idea is to get rid of "special directions" -- there shouldn't be an axis that behaves differently than the others

heady iris
#

I'd just write velocity += gravityVector * gravityMultiplier * Time.deltaTime;

#

gravityVector would be 9.81f * Vector3.down by default

dense estuary
heady iris
#

I guess I'd do it before splitting, but that's going to be a very slight change

dense estuary
#

Here is what I got:

void PlayerMove()
{
    Vector2 moveValue = move.ReadValue<Vector2>();

    Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
    desiredVelocity = SlopeVelocityChange(desiredVelocity);

    velocity += gravityVector * gravityMultiplier * Time.deltaTime;

    Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeHit.normal);
    Vector3 normalVelocity = Vector3.Project(velocity, slopeHit.normal);

    planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);

    velocity = planeVelocity + normalVelocity;

    controller.Move(velocity * Time.deltaTime);
}```
heady iris
#

hm, yeah, this doesn't have any friction

#

so gravity will send you careening off

#

See how it feels if you dramatically increase your acceleration. You should stop slipping off the slope

dense estuary
#

I step on the slope and slide up, but slower

hybrid orchid
#
    private IEnumerator TypeCoroutine(Fox talkingTo)
    {
        _dialogueText.text = fullText;
        _dialogueText.maxVisibleCharacters = 0;
        while (characterIndex < fullText.Length)
        {
            if (fullText[characterIndex] == '[')
            {
                int endTokenIndex = fullText.IndexOf(']');
                string token = fullText.Substring(characterIndex + 1, endTokenIndex - characterIndex - 1);
                Debug.Log("idx1: " + characterIndex + " token: " + token + " idx: " + endTokenIndex);
                fullText = fullText.Remove(characterIndex, token.Length);
                characterIndex = endTokenIndex + 1;
                 
            } else {
                _dialogueText.maxVisibleCharacters = characterIndex + 1;
                characterIndex++;
                yield return wait;
            }
        }
        wait = new WaitForSecondsRealtime(0.05f);
    }```
#

im trying to parse dialogue text and remove emotion prompts like [happy], [sad] etc

#

but for somereason Remove is reversed and the starting index is the end of the string and the characters to remove go backwards ?

#

like if im not mistaken Remove's first argument is the starting index then the second argument is the characters to remove after that

#

charaterIndex is 0 and token length is 9, but the beginning string isn't removed at all, a text like "[happy]Hello! how are you?" becomes "[happy]Hello! how"

fervent furnace
#
  1. given start index s_idx and end index e_idx
    the length is e_idx-s_idx+1, then remove from s_idx with length e_idx-s_idx+1, no need to create substring
  2. just move the pointer to index of ] +1
cosmic rain
#

Did you try stepping through the code with a debugger?

fervent furnace
#

wait, isnt the tmp text pointing to different string instance?

hybrid orchid
hybrid orchid
#

Oh and characterindex does become ] + 1

fervent furnace
#
TMP.text=a_str;//here a_str contains emtional prompts
a_str=a_str.SomeChanges();//.SomeChanges() returns new string, TMP.text still pointing to old a_str
hybrid orchid
opaque fox
#

Hello so for my game I gave the player some health and when a specific animation plays the player takes damage but they are immediately dying 😦 idk why https://hatebin.com/mmwsqomihu

deft timber
#

because you are substracting 50 health every frame your current animation is "Punch"

#

learn animation events

opaque fox
#

I tried but when i looked it up nothing came up

deft timber
#

then look better

#

basic googling skills

soft shard
split stirrup
#

any ideas why in webgl scenes transitions may not working( I appears in main menu, then push the play button and nothing happening(in unity editor everything ok))?

deft timber
#

make a debug build and upload it and debug

split stirrup
opaque fox
#

Well I made one of the animation events however it is saying it does not have a function name even though i set the method

hard estuary
#

What are the best practices in terms of refreshing nested Layout Groups?

astral nexus
#

how to handle UI state and its logic properly in unity? I know about MV_ family patterns, but its very sloppy to implement in the engine (at least for me)
I know it's more architectural question and I can do whatever works for me, but I just want to make "more clean" code, so I ended up doing UI manager that holds an internal event bus with all events and I just subscribe and fire these events by this manager interface
but I think there are more and more better ways of doing it, because all of my classes that interact with UI depend on this manager and its event bus
and it's very dirty and clunky to put this subscription and unsubscription all over the place in init logic of my scripts
maybe there are some resources or tutorials on this topic that you guys can share?

#

preferably for unit testing capabilities of UI classes

cunning thunder
#

Hey guys, I am far into multiplayer fps game development with Unity. I have been lately debugging my lag compensation code and it looks like one box collider is offseted little bit on server in comparison to client. (or my box collider drawing code does not work)

I am drawing using object's (which got the collider) position, rotation, lossyScale, and also box collider size + center. It also seems like lossyScale is different by about 0.001 even though it should be (100, 100, 100) on both.

My question is: how can I 100% accurately log a box collider into console? Do I just need box collider's center & size, and then the object's world to local matrix, instead of using lossyScale etc?

orchid abyss
deft timber
#

how can we know?

humble pumice
#

Soundfile, code, settings in inspector

#

Code at least

orchid abyss
deft timber
#

well look at your code

#

you are playing the audio every frame

#

when the health is below or equal to 0

orchid abyss
#

its a death sound

deft timber
#

and you are playing it every frame

slow shoal
#

Basically what you wrote is

deft timber
#

when the health is below or equal to 0

#

idk how can i explain this simplier lol

slow shoal
#

every update meaning every frame your music will play

orchid abyss
#

ah

slow shoal
#

if health is below 0

deft timber
#

learn events

#

make OnDie event, trigger it when unit dies

#

and subscribe stuff to that event

thin aurora
# orchid abyss

I assume you expect the sound to end when the object is destroyed, which is fair. However, you destroy it after the length of the sound has elapsed, and considering this code plays every frame it will invoke the sound every frame until the first Destroy call has its delay end

#

So instead destroy it immediatley and have the sound play on a separate gameobject, maybe

#

Or add a boolean to indicate this if-statement has triggered

slow shoal
#

Actually i wondered same too, even tho im not beginner

deft timber
#

it shouldn't be in Update

#

let's start from that

thin aurora
#

Depending on having a gameobject destroy itself so the update statement doesn't trigger is kinda bad to begin with

slow shoal
#

Like detect in update, and then run only once

deft timber
#

perfect event use case

slow shoal
#

How can you do that

thin aurora
#

A boolean variable?

deft timber
#

things like that shouldn't be handled in Update

reef cobalt
slow shoal
#

Yeah but that's just a poor solution

#

I think there are better solutions

thin aurora
#

Having it in an Update statement is the actual problem though

#

It should be an event handler

reef cobalt
#

I agree

orchid abyss
#

what is event handler

thin aurora
#

dealDamage should trigger an event that indicates the object died, or instead that it took damage. Then have another script handle the sound if the health reached 0 or lower

thin aurora
deft timber
#

well

orchid abyss
#

aight

deft timber
#

i just said that 3 times already πŸ˜„

thin aurora
#

My bad

#

Or make the simple fix of checking health in dealdamage if you don't want the added abstraction

slow shoal
#

And it only runs once, correct?

dusk apex
# orchid abyss

Maybe consider evaluating and setting the object for destruction after decreasing health.

thin aurora
# orchid abyss

And please consider using proper .NET conventions when writing code. This is pretty bad...

slow shoal
#

Imagine how life would be easier if discord also included line count

lucid tulip
#

It's called Enhance CodeBlocks

thin aurora
#

I don't think BetterDiscord is going to fix a screenshot

slow shoal
green ice
#

Hi guys,i have a question,i have to draw a vector but rotated,how can i do it?

#

i have to rotate it of 180 degrees in the x axis

slow shoal
green ice
#

My question is can i do it?

lucid tulip
#

Yes

thin aurora
quartz folio
#

Multiply it by a quaternion that expresses the offset you want

slow shoal
#

Here take this graph

lucid tulip
#

Good graph

green ice
slow shoal
#

Vector(1,1) is diagonal on the right upper side

#

for example

green ice
#

thanks

dusk apex
#

What's happening instead?

deft timber
#

is this chat gpt code

#

it looks like it

thin aurora
#

100%

deft timber
#

πŸ˜΅β€πŸ’«

slow shoal
#

It sure does

kind pivot
#

anyone know if there's a way to reset rich text in a string? like if the first part of a string is in rich text but I don't want the next part to be and I don't necessarily know what tags that were used so I can't just close them (user provided)

astral nexus
#

I have simple action map for UI and EventSystem component set up with Input System and it works just fine, but when I disable this action map - it still register input to IPointer_xxx_Handler and its callbacks being called just as it was enabled, but it's not
am I missing something? why its calling this callbacks even when action map is disabled?

lucid tulip
kind pivot
quartz folio
#

well, any robust solution would have to be much more involved than just that

thin aurora
#

Regex is not that bad, just don't do it inline like this

#

Because this is slow

#

There are libraries that can generate code to replace a regex query, I believe it's even is base .NET

kind pivot
#

I would just prefer not to use regex as there's always a chance it'll capture user input unintentionally possibly without a means of escaping it

lucid tulip
kind pivot
#

but I had seen a few use it as a solution on forums so I was fearing that was the only way to solve it

quartz folio
#

Consider, two parallel fields, one with rich text enabled, the other not?

kind pivot
#

but the text needs to be side by size so I'd need to adjust it using horizontal layout? idk how that would even work with multi line inputs

thin aurora
quartz folio
#

I don't use UGUI any more, so I have no good answer for that one lol

kind pivot
#

UGUI?

quartz folio
#

Unity UI

kind pivot
#

ah

quartz folio
#

I was just hoping that you might have a simple enough case where it would not be bad

kind pivot
#

tbh I'm considering just disallowing all rich text with the noparse tag. but this is more if I wanted to allow it in the future

kind pivot
modest lion
#

dafuq does that mean

  • every time i try to join the multiplayer game i created it crashes as soon as it loads into the map
#

thats also a error i am getting

#

i am super confused since this is not telling me anything

humble pumice
#

This multiplayer right?

modest lion
#

yea

knotty sun
# modest lion i am super confused since this is not telling me anything

I would have thought
Disconnecting connection: connection(0) because handling a message of type Mirror.RpcMessage caused an Exception. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: System.Collections.Generic.KeyNotFoundException: The given key '5' was not present in the dictionary.
was more than enough information

modest lion
#

yeah but what is meant by key 5

#

oh wait

#

maybe

#

i have an idea

humble pumice
# modest lion yea

I can't post invite links here, but you prop want to go to the "Unity Multiplayer Networking" server. It's generally more helpful.

modest lion
#

could you dm me the invite?

ripe cove
#

hello im having troubles with making scripts for each level of difficulty of the game we're developing, can someone help me? πŸ₯Ή

#

we're currently developing a game and our game is inspired from decked out 2

#

you may or may not be familiar with the game, but its a good one!

soft shard
ripe cove
#

So in our script 'HardDiff.cs', which is the script for hard-coded parameters for every dungeon (based on thei difficulty), every difficulty has different parameters. We're gonna put it in a single script for button event in onclick(). Now, we will inherit those parameters from different scripts such as RoomFirst script, RWalkDungeon script and Abstract Dungeon script. The RoomFirst script, is for the room and dungeon partition, then RWalkDungeon is for random iteration and the Abstract dungeon is for clearing the dungeon every generate.

#

So the predetermined parameters are:

Easy
Min Room -W - 10
Min Room - H - 10
Dungeon - W - 70
Dungeon H - 70
Offset - 2
Iterations - 50
W Length - 15

Medium
Min Room -W - 20
Min Room - H - 20
Dungeon - W - 150
Dungeon H - 150
Offset - 3
Iterations - 100
W Length - 25

Hard
Min Room -W - 20
Min Room - H - 20
Dungeon - W - 250
Dungeon H - 250
Offset - 4
Iterations - 200
W Length - 60

#

The issue is that there is a script 'DungeonData.cs' which is for the parameter editor for RWalkDungeon. We made a 'Hard' button to try. But it wont generate a dungeon.. here's the code.

#

here are the parameter script for RoomFirst script, RWalkDungeon script, Abstract Dungeon script, and DungeonData.cs

soft shard
# ripe cove

One suggestion I can make, if you want to simplify some of your repeat variables across the various scripts, you can put them all in a class, if you serialize that class you can populate it from the inspector, and if you put that serialized class into a ScriptableObject, you can even create assets of that data to reference on various objects, for example:

[System.Serializable]
public class SomeData
{
public string name;
public int health;
public float speed;
}

[CreateAssetMenu()]
public class SomeDataSO : ScriptableObject
{
public SomeData data;
}

public class SomeImplementation : Mono
{
public SomeData data;
public SomeDataSO so;

void SomeFunc()
{
Debug.Log(data.health); //assigned from inspector
data.health = so.data.health; //assigned from asset, referenced from inspector
}
}

This alone wont solve the issue you described, but it may help just having to only add "SomeData" to scripts, or referencing just a "SomeDataSO" in case your designers wanted to change the numbers at any point without having to dig through specific objects and scripts

ripe cove
#

okay will try that right away, thank you!

raven ibex
#

Hello, does anyone know how can i crop extra alpha pixels in a Texture2D in runtime, akin to Trim option in Photoshop?
I need to do that to preview the images, because otherwise the full image is going to be scaled down and hardly visible
At the same time i can't change the source image, because it's used in full for overlaying purposes

knotty sun
raven ibex
#

Yes, i'm considering this ATM, i was just wondering if cropping would be a better option, so i could keep the image clutter minimal
Thanks for responding!

knotty sun
#

it's not difficult to do but it is time consuming
you scan the pixels and make a bounding box for the non alpha pixels then you make a new texture and copy the pixels inside the bounding box into that

deft dagger
#

hey, is there a way to make tab between input fields ?

raven ibex
knotty sun
#

with alpha != 0

#

and use Color32 not Color

raven ibex
#

alright, thanks!

thick terrace
raven ibex
thick terrace
raven ibex
#

i don't really understand the benefit of this if i'm working with just the texture

#

but thanks for the suggestion

thick terrace
#

you haven't specified how you're displaying the images, but it'd be a benefit if it was a UI Image or something like that, because creating a sprite would be cheaper than copying a whole texture

quaint rock
#

they mentioned sprite since you can define a rect on a texture of the part the sprite should be of

#

though first thigns first how are you wanting to use this texture?

#

if you wanted to trim a texture and not make a sprite on it, you would create a new texture of the target size then copy only the pixels in the range you care about to it

raven ibex
#

the original texture is added into the template, so the output would be the combined texture, that is then used for an image

quaint rock
#

yes but are you displaying this on a model

#

in the UI

thick terrace
#

in the end a sprite is just a way to tell it to render the texture with the right UVs to display a region of the image, so whether or not you can use a sprite, that's an option if performance is important

quaint rock
#

via a sprite renderer?

raven ibex
#

UI image

quaint rock
#

you want a sprite anyways then

raven ibex
#

yes, but isn't that a final stage though?

quaint rock
#

since UI image does not use texture directly, so you can simple create a sprite that displays 1 area of your texture

raven ibex
#

i simply don't know how to make this to be honest, so i'm just tinkering with the source texture

quaint rock
#

if you are deadset of doing it in the texture, there is no trim function, what you do is create a new Texture2D at the wanted size, then copy what you need from the old texture into it

knotty sun
#

The trick is to calculate the Rect, what you do with it, Create Sprite or make a new Texture is not so important

raven ibex
#

i see, thank you for the help, i'll try to figure it out with what you provided

worn pecan
#

Hey guys, can you teach me how to make a player teleport?

#

I tried tutorials on youtube but didn't work.

knotty sun
#

transform.position = newPosition;

worn pecan
#

If it is possible, can you make a vid?

quaint rock
#

he literally gave you the code

real falcon
#

I'm just trying to make a player controller with netcode and the character keeps bouncing at extreme speeds into the stratosphere

quaint rock
#

teleporting is just setting a position instantly

worn pecan
knotty sun
#

you put it in your code at the point you want the player to teleport

quaint rock
#

!learn

tawny elkBOT
#

:teacher: Unity Learn β†—

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

real falcon
# real falcon I'm just trying to make a player controller with netcode and the character keeps...
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.VisualScripting;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Processors;
[RequireComponent(typeof(CharacterController))]
public class PlayerNetwork : NetworkBehaviour
{
    CharacterController characterController;
    [SerializeField] new Camera camera;
    bool isSprinting = false;
    
    void Start()
    {
        characterController = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
    }
    public float moveSpeed = 1f;

    public float sensX;
    public float sensY;


    float xRotation;
    float yRotation;

    float horizontalInput;
    float verticalInput;
    Vector3 moveDir;

    Rigidbody rb;

    private void FixedUpdate()
    {
        MovePlayer();
    }

    private void Update()
    {
        if (!IsOwner) return;


        //Camera controls
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);




        //movement
        MyInput();
    }
    private void MyInput()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
    }
    private void MovePlayer()
    {
        //calculate movement direction
        moveDir = transform.forward * verticalInput + transform.right * horizontalInput;

        rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force);
    }
}

it's using netcode as well btw

tawny elkBOT
quaint rock
quartz folio
worn pecan
deft timber
#

without understanding it

#

right

worn pecan
#

Yeah...

quaint rock
deft timber
worn pecan
deft timber
#

how is that related

#

to what i just said

quaint rock
#

like i am not trying to be harsh, but you have to put the effort into understanding things to use it

quaint rock
#

all introductory lessons on unity and C# will show you how setting positions works which is what a teleport is

quartz folio
real falcon
vital aurora
#

Can I set the "Build Configuration" and "Script Debugging" parameters in the build settings tab from script? I've been looking around EditorUserBuildSettings/EditorBuildSettings/PlayerSettings and I don't seem to be able to find anything relevant. I did find the necessary development flag I need to enable script debugging, but not the actual flag

deft dagger
#

hey is there anyway to make the tab button switch between input fields ?

thick terrace
vital aurora
knotty sun
vital aurora
knotty sun
hard viper
#

I am moving my project folder with my unity project from a mac to a new windows machine. Is there anything I should know to ensure a smooth transition?

real falcon
#

What's a good way to move the player other than transform

hard viper
#

Unity hub has an β€œadd project” button to add project from folder

#

but that sounds like a different feature

knotty sun
# hard viper wdym

Asset->Export on Mac to create a .unitypackage Asset->Import on Windows to read said pakage

hard viper
#

gotcha. and this is on UnityHub or in UnityEditor?

knotty sun
#

Editor

quaint rock
#

there is no need to export

#

just delete the library and temp folder after copying the project folder over

hard viper
#

i just want to send over to ensure as smooth of a transition as possible

quaint rock
#

yeah jsut copy the whole project folder and delete the Library folder in it

hard viper
#

i assume an explicit export/import is designed to handle that

#

i’ll give each a shot. The only thing I have to lose is a little time

quaint rock
#

at work we are using a mix of macs and windows and it all works fine. using git which ignores the few folders that are generated by unity and its all seamsless

chilly surge
#

Refer to Unity’s gitignore template to see which folders are useless.

#

It’s as simple as copying over only the actually useful ones and just open it on the new machine, nothing much else is needed.

quaint rock
#

even i have both machines on a kVM and swap between on the same project at times based on what i am building for. like need windows to build for switch for example

#

also i heavily recommend learning about version control and Git

hard viper
#

ty. I’ll need to check it out

#

i guess on a different note, let’s say I have a mac and a windows PC, and I want to be able to interchangeably work with either on the same project. What is the best way to sync everything?

#

github?

chilly surge
#

Any version control.

quaint rock
#

any version control

#

though Git with Github are most popular

hard viper
#

which would you recommend?

#

I haven’t done ssh since my college years

#

don’t even remember what it stands for. just have that memory lol

knotty sun
quaint rock
#

really once the ssh key is setup its not something you have to worry about again

chilly surge
#

I personally use git yeah, but supposedly it doesn’t work that well for large binary assets. My projects don’t have a ton of large assets for me to really know if that’s true.

quaint rock
#

i setup the ssh keys for git on my mac like 5 years ago and never touched it again

#

@knotty sun shared drive would be very bad for this due to the Library folder

latent latch
#

local repositories for larger assets

quaint rock
#

would need to nuke it everytime and let it regenerate which is a waste of time

hard viper
#

i see. is there a guide/resource/tutorial on how to best set this up?

#

i think you are saying to set up a git with an ssh key.

knotty sun
hard viper
#

they probably all do work. but version control is probably better to revert

chilly surge
#

For git, it shouldn’t be much different from other projects. Have your credentials setup, have the Unity’s gitignore template setup, then just commit/push/pull/etc like you normally do.

knotty sun
#

you should have version control whatever else you do

hard viper
#

yeah, I’ve been bad

quaint rock
#

you get other bonuses with a full VCS system too, since you can revert to past versions easily and see diffs which makes tracking down bugs much easier

hard viper
#

are there any privacy issues?

quaint rock
#

can work on features in isolation from other changes and easier collobration

#

depends on where you host it, but pretty much any provider will have private and public repos

knotty sun
#

only, if you use Github, MS will steal your project to train their AI models

quaint rock
#

so just use a private one

#

they only do that with public repos not private

chilly surge
#

Also to note git is not tied to GitHub/GitLab/other hosts, you are free to use git completely offline or self host if you want.

hard viper
#

so i should use git

quaint rock
#

yeah git is the system and protocal GitHub,GitLab,Bitbucket etc are all just cloud providers for the remote

#

some people might recommend unitys vcs system, but i greatly prefer Git, and its the standard for most software development these days

#

gamedev and animation are the main exception where Git is not the defacto choice, but still common in this domain

vagrant blade
quaint rock
hard viper
#

ty all.

quaint rock
#

like if you want to use physics use a rigidbody, if not use a transform

real falcon
#

How do you use a rigidbody as I tried that and it didn't move

#

rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force);

rancid basin
#

i got a climbing script in unity for VR but it should be the same as for 3d just the hand being the player so im asking this here and i have some issues with it.

the first issue is that if i start climbing on a object i get teleported a little before my hand is at the position it should be again.

the second issue is that its responding too slow. its smoothing my movement out which it shouldnt it should be moving my player exactly when im moving my hand too.

this is the part that is handling the climbing which is in my FixedUpdate() void:

Vector3 deltaPosition = currentObjectClimbingOn.position - lastHandPosition;
        rb.MovePosition(rb.position + rb.transform.rotation * deltaPosition * 10f * Time.fixedDeltaTime);
        lastHandPosition = transform.position;```

i already tried removing the Time.fixedDeltaTime and also tried changing the multiplier from 10f to something like 100f or 1f but with 100f or no Time.fixedDeltaTime im getting flung around and with 1f the movement is even slower.
hexed pecan
real falcon
#

yes

hexed pecan
#

Oh seems like you are trying a rigidbody already

storm thorn
#

Hi! Do you guys have any idea for pdf generator in unity that can work on android?

real falcon
#

Yeah, I've got this rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force); Physics.Simulate(Time.deltaTime); (surely this doesn't count as big enough to be put in hastbin) but it doesn't seem to do anything and I don't know why

hard viper
#

is your rigidbody dynamic

real falcon
#

no

hard viper
#

then add force will never move it

#

it is not affected by forces

hexed pecan
#

^ Also why are you calling Physics.Simulate manually

hard viper
#

also you should not need to call Physics.Simulate unless you have an extremely good reason to, which you don’t

real falcon
#

the docs said something along those lines

hard viper
#

well, I’m telling you no

#

Physics.Simulate runs the entire physics simulation by that timestep

real falcon
#

play still can't move

hexed pecan
real falcon
hexed pecan
hard viper
#

Unity by default runs Physics.Simulate(fixedDeltaTime) at the right time, every fixed frame

#

do not call Physics.Simulate unless you are making a custom physics system or something.

real falcon
#

rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force); I have this in void Update but nothing happens and I also have this for input system if (Input.GetKey(KeyCode.A)) horizontalInput += 1f; if (Input.GetKey(KeyCode.D)) horizontalInput += -1f; if (Input.GetKey(KeyCode.W)) verticalInput += +1f; if (Input.GetKey(KeyCode.S)) verticalInput += -1f;

hard viper
#
  1. If your rigidbody is not dynamic, adding force will never move it
#
  1. you have not checked if the vector going into Addforce is non zero, which is a separate check
real falcon
hard viper
#

that is a different setting

#

i’m talking about dynamic vs kinematic

real falcon
#

well it's got kinematic off

#

and there isn't a dynamic option

hard viper
#

for 3D, not kinematic means dynamic

#

check the vector being passed in to add force

#

with Debug.Log

#

if the vector is small or zero, that needs to be resolved first

real falcon
hard viper
#

and the script is on a monobehaviour on the object

#

and the addForce is in FixedUpdate

real falcon
#

the script is NetworkBehavior

hard viper
#

but does it derive from MonoBehaviour

real falcon
#

yep

#

I think

hard viper
#

how do you not know

#

you wrote it lmao

vital aurora
real falcon
#

no its from netcode

#

but also I control clicked it in visual studio and the file defining it was monobehavior

hard viper
#

before you try importing any code into unity, you should at least know the basics, man

#

you don’t know how to drive, and you’re on the highway

real falcon
#

I can still walk confidently

hard viper
#

start by writing code from scratch without importing

real falcon
#

I mean I did a bit of that

hard viper
#

you should be putting the whole script in hastebin tbh

real falcon
#

I gtg now but thanks for the help!

full sail
#

so i got this track that i made with splines out of a prefab which looks like a hollow cube, but i noticed that there are overlaps between tracks in narrow parts, and large gaps in sharp turns, so i reduced the distance between them and tried to link the vertices with probuilder but i later realised when i baked the instances that there are more than 150 instances that i need to link vertices of, and not only that but you can't "Weld Vertices" of two different gameobjects anyway, so i am asking here is there a way to link the track visually in a way that 1. won't need me to join between gameobjects (because i have some logic that uses the rotation of each gameobject and it's transform.forward to determine camera rotation) and 2. something that wouldn't need me to go making an algorithm using the Mesh class and merging vertices that way since i don't know a lot about it and it can break in a million ways with normals, lighting, texture etc...

full sail
glossy wave
#

Hello! I am trying to make my Enemy detect the Player using a Spherecast, but it doesn't seem that the Spherecast is hitting the Player, because I'm not seeing the Debug.Log() message. In the screenshot, the transform gizmo is the origin of the spherecast (raycastOrigin.position in the code), and where the arrow i drew points to is the origin of my Player (player.transform.position in the code).

        raycastDirection = raycastOrigin.position - player.transform.position;

        if (Physics.SphereCast(raycastOrigin.position, 0.05f, raycastDirection, out hit, raycastDistance))
        {
            if (hit.transform.CompareTag("Player"))
            {
                Debug.Log("<color=red>Enemy sees player!</color>");
                result = true;
            }
        }
green ice
#

Guys lets's say that a person uses the method LookAt() but looks that target objects with the back of the head,how can i look the tarket object with the front of the head?

steep herald
hard viper
full sail
hard viper
#
  1. spherecast only returns 1 hit when you want a boolean output
#

so if you have multiple hits, and the first one isn’t the player, but the enemy, it will return true with a hit of the enemy

#

also, your spherecast should restrict search to relevant layers

steep herald
# full sail Joining game objects and welding vertices or using the mesh class? Also how can ...

Generating a mesh dynamically.

I don't know the unity spline system but generally you break down the spline into a polyline with smaller segments who's lengths are closer to even. It's useful for navigating the spline at even speed if you're using the actual spline for navigation.

You can get the spline's forward vector by sampling the spline/polyline at ((p + some small value) - p).normalized. I'm sure unity already has something for this tho but I can't speak to it.

#

as for the mesh generation, under its most basic form

  • sample all points (or break down into polyline and figure out the target length for the resolution you want)
  • figure out the width you want, find the forward vector at the position of point and create verts at -perpendicular vector * halfWidth, another one at perpendicular * halfWidth.
  • If you want your road to have thickness, offset 2 more vertices based on those vertices and the relative up negated
  • repeat for all points
    then just read the mesh generation doc, it's like a 5 minutes read, it'll explain the order of triangles and a few more things that are really simple to grasp but seem scary in nature
glossy wave
hard viper
#

yeah, I would use a method that returns a list of RaycastHit, and then sift through to find valid hits

#

I would also include a layer mask, because the enemy’s eye should be on a layer that does not get included in your query, probably

glossy wave
#

Thanks

tardy crypt
#

when you have a regression and then notice you have no idea why it occurred because your code is spaghetti...

#

i hope everybody is ok with me sharing my stupidity

rigid island
#

eg your Forward is wrong

green ice
#

Yes,by default the pivot is wrong

#

Is there a way to fix it?

rigid island
#

show your current object, make sure Local / Pivot mode is selected

green ice
rigid island
green ice
#

I will try later thanks

#

no but you could make a thread here if

prisma birch
#

How can I exclude an object or component that is part of a prefab from being recorded as an override?

hard viper
#

i’m not sure what the use case is here

#

it’s in the prefab, so you want it to come with the prefab. But you want to make edits to it, and not log that it is editted?

prisma birch
#

I have instanced materials on the object that need to be unique per object

#

So as soon as I add the object to a scene it comes with an override

leaden ice
#

What's the issue with it having an override?

prisma birch
#

That it makes the object appear to have been modified in the scene, but by nature it will always appear overridden

leaden ice
#

Also I assume you mean when you add it in the editor? I guess you have an editor script doing the material instantiation?

prisma birch
#

Yes

leaden ice
#

Well it is overridden...

prisma birch
#

I know

#

But I'd like to ignore that specific override

hard viper
#

why

leaden ice
#

But then the material change won't be saved right?

prisma birch
#

so I can more properly track prefabs that have been truly overriden

hard viper
#

to not be overriden means it matches the prefab

hard viper
prisma birch
#

but it can't match the prefab because the material is instanced on the prefab

#

so it will always appear overriden

hard viper
#

i just don’t understand what the issue is here

#

it is overriden, because you did override it, and that it why it appears overriden, because overriding is what you did

#

i feel like I’m talking to patrick star

prisma birch
#

The issue that I would like to ignore specific overrides, I'm not asking you to understand the specifics of my project

reef garnet
#

Hi I'm working on my own custom input tool that builds on top of the input system that uses scriptable objects as events. Now conventional wisdom says that I won't be able to do exactly what I want to do without some sort of grouping (list, array, etc...), can you loop through every reference of a type of variable in a script? I want to use it to automatically generate the event scriptableobjects. In essence I want the function to go through these variables in the image below and create an event object with the same name and then assign it.

prisma birch
#

being able to know when an object is overriden is useful but this specific prefab will always appear overriden and it's an override that I don't care about

hard viper
#

then whatever editor script you made needs to explicitly check for that. probably OnValidate

reef garnet
hard viper
#

you are asking for Unity’s prefab system to propagate changes in a way that is more tailored to your specific use case, which diverges from the standard

#

and that is ok, but that requires specific code for it

hard viper
#

storing events in an SO during runtime for transient input events sounds like bad juju

heady iris
#

Reflection would allow you to iterate over all of the members of the type, yes

#

I have a vaguely similar situation where I need to both have specific fields and have a list of all of the things in the fields

#

in that case I just accept the duplication and make sure I put things both in a field and in a list

#

(I have an editor script that verifies this, through reflection)

reef garnet
heady iris
#

I could probably just switch to using reflection at runtime.

hard viper
#

reflection is the way to go here

craggy veldt
#

TypeCache should be faster than reflection, use that instead of reflection

#

assuming it's for edit-mode

hard viper
#

anyway, the bigger thing is: you probably don’t want to use SOs for this

craggy veldt
heady iris
#

ah, so it just caches the results of reflection for you

#

handy

craggy veldt
#

it's way beyond that, it's natively cached

timid depot
reef garnet
timid depot
#

im slowly starting to hate this game engine

west lotus
#

What exactly is the bug here ?

timid depot
#

look at limits

#

when I de-active element and re-active it

#

limits are relative to current local rotation

#

you can't imagine how long i've been debugging it for

west lotus
#

Hmm that does indeed look like a bug. File a bug report for it

timid depot
#

where can I do that?

craggy veldt
#

usually when people say that, they will still using it for years

hexed pecan
#

Oh sorry I was scrolled up

thin oxide
#

I'm already going crazy

#

the same script that perfectly found the object I want, it says it doesn't exist

#

how is this possible

#

HOW find something that doesn't exist

timid depot
#

it suits best my game and there's nothing better (maybe unreal but for graphics)

craggy veldt
#

I'm using both for work, UE ain't as nice as what you're seeing or heard either.

thin oxide
spring creek
spring creek
timid depot
thin oxide
rigid island
thin oxide
#

RadioSystem.cs//InterectSystem.cs

rigid island
#

send the whole script

#

!code

tawny elkBOT
rigid island
#

!screenshots

tawny elkBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

thin oxide
#

!code public void OnClickInterectEvent(GameObject ObjectSelected)
{
if(ObjectSelected == radioObject)
{
Debug.Log(radioObject);
cursorDetectorScript.SwitchCamera(5);
RadioTutorialCanvasAnim.SetBool("TurnOnRadioAlarm", false);
radioInterect = true;
}

}
tawny elkBOT
thin oxide
#

I didn't understand how "!code" works

tawny elkBOT
rigid island
thin oxide
rigid island
thin oxide
#

but thanks for letting me know

thin oxide
spring creek
# thin oxide ok bye

When you come back, we want the WHOLE script. Use a paste site as described at the top of those messages

real falcon
#

if a rigidbody is restraining rotation of an object, how can I make a script follow these constraints as right now it is just rotating freely

spring creek
#

But not from you moving it

real falcon
#

how can I change that

spring creek
#

You just have to clamp rotations yourself

real falcon
#

can I rotate it through the rigid body

spring creek
real falcon
#

how

#

because I tried rigidbody.rotation but it was still not following the constraints

hexed pecan
#

try rigidbody.MoveRotation

#

Not sure if that respects constraints πŸ€”

spring creek
#

I'm almost certain it does not, but it was a while ago that I tried

hexed pecan
#

AddTorque does at least

real falcon
#

it doesn't

spring creek
#

Other option is rigidbody.rotation
And yeah, AddTorque

hexed pecan
#

They tried it

rigid island
#

AddTorque cause iirc is similiar to addforce no?

#

but rotation

spring creek
# hexed pecan They tried it

Oh, they asked how to rotate with a rigidbody, so I didn't think they tried anything, and instead did it with transform

real falcon
#

how do I turn my quaternian for rotation into a vector 3 for addTorque?

hexed pecan
#

Quaternions have .eulerAngles

#

Note that you shouldn't just plug in the target rotation in it

#

You need a difference from your current rotation to the target rotation

#

Just like you don't give AddForce a position, you give it a direction/force vector

real falcon
#

would it be easier to just clamp it?

rigid island
#

you havent even explained your usecase, how can we know whats better /easier solution

real falcon
#

it's a playercontroller with a rigidbody

hexed pecan
#

Just to make sure - it doesn't have a CharacterController component right?

real falcon
#

It did but it seemed to make the character go flying randomly

hexed pecan
#

Yeah rigidbody doesn't work with CC

rigid island
#

well yeah its collidng with rigidbody (making rb fly off)

spring creek
real falcon
#

found that out the hard way

spring creek
rigid island
spring creek
#

AddForce, Velocity, or MovePosition

hexed pecan
real falcon
hexed pecan
#

MoveRotation respects interpolation while rotation does not

real falcon
#

I'm not sure how to clamp the character without clamping the camera because it's first person

#

wait nvm

split plover
#

does anyone have a good solution for hiding changes to files that need to exist in the repo but that do not really want to have changes made but for which unity makes changes often (eg, a material which has a property set in play mode) - technically we could clone the material but its kinda a pain to update references since its used in a ton of places. I previously wrote an onquit script to revert it but it looks like that has broken. I'm thinking of trying git assume-unchanged or git skip-worktree

real falcon
#
``` Why can't I do this and how would I clamp the x rotation of this object (camera)
heady iris
#

so, two things

#

transform.rotation.x is not an angle. It's the X component of a quaternion.

#

and that's an error because transform.rotation is a property, which returns a copy of your current rotation

#

modifying this would be pointless, so you get an error

real falcon
#

so how would I do this

heady iris
#

I would suggest storing the desired rotation for the camera in a float

wicked river
#

I can't seem to see a channel where I would ask about Muse Behavior so I will ask her and anyone can just point me to the correct channel.

I am currently trying to learn how to use my own sysorySystem script with the muse Behaviour tree. I keep getting a null reference when trying to gain access to the script.
Any info, links or tutorials on the topic would be highly appreciated .

heady iris
#

You can try to clamp the euler angles of the transform, but this can cause some unwanted behavior

#

for example, -30 and 330 are equivalent

#

So you might wind up being unable to look down if transform.eulerAngles spits out 330 instead of -30

heady iris
#

then just set your rotation directly

real falcon
#

well all I need from this script is to stop my fist person player from looking too far down or up

heady iris
#
transform.rotation = Quaternion.AngleAxis(yaw, Vector3.up) * Quaternion.AngleAxis(pitch, Vector3.right);

that's how I do it

#

I think Quaternion.Euler(pitch, yaw, 0) would also work but I'm not 100% on that (maybe the order of operations will be wrong?)

wicked river
#

Muse Behaviour

rigid island
#

someone's actually paying for that?

wicked river
rigid island
#

muse is a subscription

#

I cannot even find docs for Muse behavior so πŸ€·β€β™‚οΈ

heady iris
#

i was trying to read about that

wicked river
#

Ya that is why I am here

#

to ask

rigid island
#

typical unity

heady iris
#

i could only find a really trivial example

rigid island
#

release half-baked features with no to little docs

wicked river
#

I just need to figure out how to gain access to scripts

#

The NPC is fully patrolling already

rigid island
#

hard to know what the methods are withou docs πŸ€·β€β™‚οΈ

wicked river
#

just need to learn to get access to my scripts via blackboard keys

wicked river
#

there are docs though

rigid island
wicked river
#

1 sec

wicked river
#

It is also free to use

#

I have no subs

#

Muse AI needs a sub but this does not

rigid island
#

if thats true, prob because its pre-release

#

but be assured Muse IS a paid sub

wicked river
rigid island
#

also you need to show which line of the script is throwing you NULL

rigid island
rigid island
wicked river
#

Ya so the variable is Balckboard<Variable>

#

or I think it's suppose to be

rigid island
#

SensorySystem = // stuff
instead of SensoryStem sensorySystem = // stuff

wicked river
rigid island
#

well you certainly dont fix a null by removing the variable name xD

wicked river
rigid island
wicked river
wicked river
#

Value is null though

#

so I assume

#

we don't get references like that

rigid island
#

"thats not it", meanwhile Value is null lol

#

go for it if you'd like

#

trying to find something more in this package

wicked river
rigid island
rigid island
#

I can look into it and study it up I'd be interested in exploring this example maybe video it

#

I gotta run out for a few hours so can't look till later

wicked river
#

THis is where I got the idea

#

from that example

#

the animatorObject.value.GetComponent

rigid island
#

are they seriously using .Find ?

#

πŸ™„

wicked river
rigid island
wicked river
#

so I guess I am stuck with find

#

will try it out and see if there are better ways later

heady iris
rigid island
real falcon
somber nacelle
#

also show your !code properly when asking for help. showing it in a video is one of the worst ways to share it

tawny elkBOT
rigid island
timid depot
#

sorr

swift falcon
#

I am using Physics.OvelapBoxNonAlloc to detect something while trying to avoid the garbage allocation.

private static Collider[] hitResultsBuffer = new Collider[1];
Physics.OverlapBoxNonAlloc(position, size, hitResultsBuffer, Quaternion.identity, LayerMask.GetMask("Enemy"))

But the second line do allocates a garbage! Is it normal? Allocation is 40B but it can stack up so i cant dismiss that. Am i using that method wrong?

#

It seems something wrong in native side

leaden ice
#

GetMask takes a variable argument list

#

C# handles that by creating an array

#

cache your layermask

orchid abyss
#

what's wrong?

vagrant blade
#

You have an interactor component in your scene that doesn't have a point assigned.

orchid abyss
#

it does tho

naive swallow
# orchid abyss what's wrong?

The variabe _interactionpoint of interactor has not been assigned. You probably need to assign the _interactionpointvariable of the interactor script in the inspector

vagrant blade
#

The one you showed does. Doesn't prove there isn't one out there that doesn't.

quaint rock
#

you have more then 1 of these in your game

naive swallow
quaint rock
#

or something destroyed the object its referencing

orchid abyss
vagrant blade
#

How did you verify that to be true?

naive swallow
orchid abyss
#

oh woops the camera also has the interactor

#

dk why

naive swallow
orchid abyss
#

ooh its from a diff tutorial

thorny osprey
#

So unity has UnityEvents which work really nicely, and can be invoked, and from the inspector work in an awesome way where you can just load up any number of functions an event

I'm wondering if it is possible to do a similar sort of thing in the inspector but with a variable rather than a function

To maybe help make it more clear what I'm trying to do, is something like this image below, but instead of the "Value" being a bool check mark, it is a selector where I can select any of the public variables from the above script. is anything like this possible?

#

like see how an event works with functions and a list, i really would like to be able to do a similar thing with variables

astral nexus
#

how to handle persistent ID for prefabs between scene loads and maybe game sessions? I can't figure it out for non very bad or sloppy way of achieving it

naive swallow
thorny osprey
naive swallow
soft shard
thorny osprey
# naive swallow https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-st...

Intersting... I'm not entirely sure that helps my case as UnityEvent was really more of an example than what I need

Basically what I'm trying to do is have a list, like a UnityEvent, where I can select variables/properties on a script and their state. I'll call this list like "requirements"

Then, I need to go through the "requirements" and see if every variable in the list meets the chosen state... I assume that a property in an event is calling set and not get, right?

I basically need it like this, but instead of setting Test to false, I just use get and return true or false if it is equal to what I have here (unchecked, so false)

#

Idk if that makes any sense lol

honest kestrel
#

is there a way to export the way the bones in an animation move mathematically?

#

ie what transformations were applied to the bone

astral nexus
# soft shard What is it your trying to do, where you need to persist a prefab across game ses...

I'm bad at explaining (and made a mistake when I typed my last message, I meant only between scene loads, not gamesessions, lol)
I want to store a UI data between scenes separetely from my UI elements, so I can just put my old state into new instanced prefabs of my UI views and it's ready to go
I can't just use type as key, because view elements can be multiple of the same type but different in data values (like labels and buttons)
for data store I've used scriptable objects, yes, but I dunno what to do with loading UI elements of the same type and different data associated with them, so I was thinking about GUID or something similiar, but I can't figure it out how to setup it's generation properly

unreal ingot
#

If Im making something like a conveyor belt to move an object that is touching it, is it best to

  1. add a small amount to the position every fixed amount of time
  2. set the velocity of the object to a certain amount
  3. add a force to the object
orchid abyss
#

i dont get it

quartz folio
#

Your method is not declaring a body, you have a semicolon here.
The next error is probably telling you that the { is unexpected.

orchid abyss
#

ah

soft shard
# astral nexus I'm bad at explaining (and made a mistake when I typed my last message, I meant ...

Ah I see, static variables exist in memory so their data doesnt rely on the state of scenes, and ScriptableObjects exist as assets in the project, which also doesnt rely on the state of scenes, however you can also create ScriptableObjects at runtime as instances, which are not files yet, and exist in memory, which also means they can persist across scenes, so any of those 3 options could help if im understanding what your trying to do correctly - with a GUID, I think that might be a bit overkill, though youd want to make sure you only register the GUID once for that object when it is initially created, and then store that GUID in some kind of static list or file so it exists in memory or accessible through System.IO, then you can read that file on the next scene or access the static list and compare the GUIDs in the list to your prefabs matching the same GUID, though that still uses static where the former may be a little less involved to implement imo

thorny osprey
#

Ok I have anotehr question similar to earlier lol... is it possible to
a) have delegates show in the inspector, or
b) have unity events return a value other than void

quaint rock
#

unity events can pass data

#

you can have a UnityEvent<int> for example, and when you invoke it can pass it int into invoke and all subscribers will get it

thorny osprey
#

I'm thinking more like, a UnityEvent which has X functions loaded in it on invoke, then if all of X functions return true, the event returns true, otherwise the event returns false

#

I know thats a little weird, which is kind of why I thought delegates would be my solution, but those don't work in the inspector AFAIK

quaint rock
#

yeah not something you could do in the inspector directly

thorny osprey
#

i kind of need it to be for what I'm doing lol, otherwise ill have to hard code so much stuff... do you know of any alternatives to what I'm thinking? i just need a way to have the functions, or even variables, that the event/function is checking to be determined in the inspector

quaint rock
#

interfaces, or abstract classes

#

reference objects that have a common interface method to call for it

dusk apex
#

Reference the component and implement how they'd interact through script.

quaint rock
#

really virtual or abstract methods on a common type would do it

#

since they you have your list of them, and can loop and get the return from each one when calling the method

thorny osprey
#

and that can be assigned via the inspector?

quaint rock
#

yeah since you are just dragging in a regular component reference

#

they all just share a common base type that has a abstract or virtual method

thorny osprey
#

so if im understading this right, i do a virtual function, say CheckRequirements() and then use an interface to add the inspector functionality? sorry if im slow here ive never used interfaces before lol

quaint rock
#

well due to a quirk of unity you cant use a interface for the part in the inspector

#

so would give all the things that should have CheckRequirements a common base type

#

that has the virtual method CheckRequirements they can override

thorny osprey
#

The things running CheckRequirements would all be on the same script, but the functions to be loaded (to be checked) wouldnt necessarily

#

well

quaint rock
#

yeah that is hte idea

thorny osprey
#

alright then I guess im just not understanding which part enables the inspector aspect lol

quaint rock
#

the thing calling CheckRequirements would have a list of BaseRequirement on the inspector

#

then anything extending BaseRequirement can be put in that list

#

and each of those things can override and define there own CheckRequirements methods

thorny osprey
#

okay im understanding what you mean now, but I'm not sure thatll solve my problem either cause the classes i'm looking to get the data from wouldnt be extending the one with CheckRequirements, they are MonoBehavior

cosmic rain
#

Make them extend the CheckRequirements...πŸ€·β€β™‚οΈ

quaint rock
thorny osprey
#

ok its gonna take me like an hour to wrap my head around this but i think this might be what i need

#

thank you

quaint rock
#

yeah not fully sure what you are trying to do, but that is one way of doing it

#

instead of needing to manually drag to the list, also would be doable to just have each requirement as a component you add to the same object then on Awake you get all of them at once save to a list then use that to evaulate things later

thorny osprey
#

so in your example, you are putting SomeReq into the list of BaseReqs right?

What if I needed to have a list of BaseReqs, then something reference BaseReqs, then my SomeReqs reference that something

So like here is my kind of layout

I have an Interactable (contains CheckRequirements())
then I have BaseReq
then Bucket : BaseReq, this has property isFull
then I have a Bucket_IsFull : Bucket, overrides CheckReq to return the isFull propetty
but I cannot put the Bucket_IsFull script into the list of BaseReqs

quaint rock
#

SomeReq can is stored in list of BaseReqs

#

anything virtual/abstract in BaseReqs can be overridden in the stuff extending it

#

and when you call it, you will get the overriden version

thorny osprey
#

and what about a double dependency

like for me it basically goes BaseReq<--Bucket<--SomeReq

#

i can't just go from BaseReq to SomeReq unfortunately cause I have properties in other scripts I need to reference, like the isFull in my bucket example

quaint rock
#

thought you would just check that in the overriden method to decide if it returns true or not

#

like the things extending BaseReq can be what ever you want, they just must implement its abstract methods

#

and you can have multiple thigns in the inheritance chain though it would recommend not making it long and complicated

rancid frost
#

does anyone know why my events either lose reference or get unsubscribed after being serialized or say after you make changes to script and unity reloads

wicked scroll
#

anything you reference in a prefab much be within that prefab, another prefab, or an SO

rancid frost
#

the problem is that when I make changes to the code, that event is unsubscribed and I have to resubsribe it

wicked scroll
#

yeah unity isn't going to serialize that (unless you make it a unityevent?) event

#

there's probably a better way to do what you're trying to accomplish that doesn't rely on that

rancid frost
#

im open to suggestions

#

I could use OnValidate method but that is messy

wicked scroll
#

does this need to happen at editor time? I guess I would just populate the meshes with whatever they need at runtime

#

if there are a lot of potential options they could ahve

rancid frost
#

both

#

Im making something similar to tilemaps

#

user should be able to make map with editor and during runtime

wicked scroll
#

then you can couple it to unity instead of to your scene and scene objects so that your events or whatever you're doing persist

rancid frost
#

ok, Will do

quaint rock
#

it will be hard to do it via events, since that will get nuked on all domain reloads

#

might have to be a editor scripting type thing where it queries for all the things it applies to and applies it

rancid frost
#

huh

#

what if i check for a change in the update method?

jagged snow
#

spawnInfos[i].OnRemove += () => { Destroy(gameObject); };
is there a reason why i cant assign this action?
: Cannot modify the return value of 'List<SpawnInfo>.this[int]' because it is not a variable

#

hmm looks like it worked after i made one inside the for int loop

fervent furnace
#

indexer is method, so

spawnInfos.Get(i).OnRemove+=
#

also notice delegate is immutable as string

jagged snow
#

it's a struct so its not possible

#
            spawnInfo.OnRemove += () => { Destroy(gameObject); };```
#

This worked

lyric belfry
#

I am trying to use Array.IndexOf(instantiatedGameObject) to get the index of itbut the array itself was made inside the editor with prefabs.

IndexOf() is returning me -1 which means it can't find the gameObject in the array. This seems to be because the reference to the instantiated gameObect is not the same as the prefab itself inside the array. Not sure what to do

The picture shows the current values of things and the lists I am accessing

#

The gameObject is BallistaTowerLv1(Clone) and the list has the original BallistaTowerLv1 prefab.

#

My main question: How can I get the index of the BallistaTowerLv1(Clone)

quartz folio
lyric belfry
deft dagger
#

hey, i have a place in my multiplayer game where when you go there another scene loads additively normally when there are more than 1 player and someone goes there the new scene only loads for the player that entered that area.
but if the host enters the area before the others join. when they join the scene loads for everyone that joins after the host entered the area.
how do i fix that ?

rancid kindle
#

idk i started getting errors all of a sudden

#

didnt even change the code, just opened up unity and so many errors

knotty sun
tawdry lake
tawdry jasper
#

For a simple interaction/melee system would you recommend putting a collider on the swinging weapon/item, or have a box collider / physics cast in front of the character? I'm using the latter now, but my code is becoming quite messy. I think both solutions will end up with situations where it looks like you should have hit something but you didn't or you did but it looks like it shouldn't so I'm mostly concerned with minimizing code and making use of standard unity features.

tawdry jasper
# tawdry lake any clue how i can fix that glitchy transition

It does look "of" but it's hard to tell whats happenning (to me), open up your character animator state machine, put in a scaled time=0.2 in editor/time settings and observe what states and states transitions are happening. This helped me debug stuff in the past. Maybe you'll see what's wrong (like a state is playing twice, or something like that)

rancid kindle
knotty sun
rancid kindle
#

wait lemme just try restarting the project once

#

ye ther errors went away lol

deft timber
#

this is a code relation channel

orchid abyss
#

my bad

round violet
#

is there a way to get the script of the built in nodes in visual scripting ?
i would like to understand how they make coroutine nodes

dusk apex
sonic swan
#

guys i have a question

#

RaycastHit2D groundInfo4 = Physics2D.Raycast(transform.position, Vector2.down, 5f);

#

instead of down i want it at a 45* angle

#

i got it working

#

nvm

amber scroll
#

how to get final velocity from a projectile after penetrating an armor plate?

latent latch
#

well, can't really expect us to work out the math for you if that's what you're asking and honestly quite ambiguous.

#

like, give us a little more information as are you using rigidbodies and setting density onto this object?

hoary quarry
#

I created a post on the forum for a problem with QueryLobbyAsync, anyone that can help me? πŸ˜„

livid kelp
#

Hey there, I am wonder if I am able to control the windows OSK.exe postition from unity?

deft timber
#

osk? virtual/screen keyboard?

livid kelp
#

on screen keyboard

deft timber
#

i dont reckon there is any built-in solutions

livid kelp
#

public IEnumerator PositionOSKBottomLeft()
{
yield return new WaitForSeconds(3);
// Find the OSK window
IntPtr oskWnd = FindWindow("OSKMainClass", null);
if (oskWnd != IntPtr.Zero)
{
UnityEngine.Debug.Log("OSK window found.");

      bool setPositionSuccess = SetWindowPos(oskWnd, HWND_TOPMOST, 0, Screen.height - 300, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW);
      if (setPositionSuccess)
      {
          UnityEngine.Debug.LogError("OSK position set successfully.");
      }
      else
      {
          UnityEngine.Debug.LogError("Failed to set OSK position.");
      }
  }
  else
  {
      UnityEngine.Debug.LogError("OSK window not found.");
  }
  yield return null;

}

deft timber
#

you'd need to make your own

#

or use this asset

livid kelp
#

ah thanks so much, how did you know?

deft timber
#

what?

#

how much did i know about what

livid kelp
deft timber
#

no clue what are you talking about :d

#

how did i know about what?

livid kelp
#

i meant like how did you figure out but I don't think this will work

deft timber
#

but how i figured out what

#

you asked for OSK i answered

livid kelp
#

yes I know

#

wrong type sorry

#

Im talking about this microsoft one

deft timber
#

idk man i think you're lacking some english πŸ˜„ read what i wrote again

livid kelp
#

I'm not I thought that was the integration for the actual microsoft integration, however I am looking to control the actual microsoft osk

#

So I asked how did you figure out how to solve this issue but we are thinking different things

livid kelp
dense rock
#

!code

tawny elkBOT
dense rock
#

A prof of mine showed a way for a singleton base class he uses. I just copied it and used it for my project.
However, I get a the following error from one of my singletons:

Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)
The following scene GameObjects were found:
Global Game Controller

Cant find solutions online, can someone tell me whats going on or whats the problem with the scripts?
Singleton: https://paste.ofcode.org/YVBvgcU8LV4kWZ9HCxCQSJ
Global Game Controller: https://paste.ofcode.org/WSUrLW9kQCMr2uHaWKQN23

thick terrace
dense rock
#

hmm i dont think there is something like that. The weird thing is, i just click the play button in my game scene a couple of times. Most times the error doesnt appear, but every now and then it does.

trim schooner
#

too much duplicated code in that singleton too

chrome berry
#

I'm making a drawer for a serializable class, and running into some issues.
I've got the serialized property for the class, and in it is a reference to a scriptable object.
I'm trying to read a boolean off of that scriptable object, but doing this:

var statBlueprint = property.FindPropertyRelative("_statBlueprint");
var canDamage = statBlueprint.FindPropertyRelative("_canDamage");

Gives me null for canDamage. _canDamage does exist as a private serialized bool in the StatBlueprint class. Am I missing some in-between step to retrieve it?

#

statBlueprint is not null, so it's not that

deft timber
#

how did you make sure

#

its not null

chrome berry
#

Ah, wait, found what I actually needed to do:
StatBlueprint statBlueprint = property.FindPropertyRelative("_statBlueprint").objectReferenceValue as StatBlueprint;
And now I can read all the fields from the statblueprint in the class

static matrix
#

what does lock do?
I'm trying to learn a bit more scripting and it looked like an interesting keyword to understand

chrome berry
static matrix
#

the more fancy purple words I use, the more dopamine my brain receives

static matrix
#

there seems to be a lot of multithreading stuff I do not understand

chrome berry
#

It's definitely an advanced topic when it comes to Unity games, most will never use them

fervent furnace
#

shorthand for creating critical section

chrome berry
#

Though it looks like I fixed it at some point, as I'm not getting the issue anymore

quaint rock
clever lagoon
# dense rock A prof of mine showed a way for a singleton base class he uses. I just copied it...

Everytime you even LOOK at Singleton<T>.instance it will create a new one, if one doesn't exist. I'd guess that something is doing that after you start closing the scene- it might be in OnDestroy, or it might be a response to a timer/event. IF this only occurs when the game is closing/quitting you can monitor this event, set a flag, and NOT create a new singleton instance once triggered. https://docs.unity3d.com/ScriptReference/Application-quitting.html

tulip hollow
#

Hello I have run into a problem while working on my fishing top down game: I have a script for random generating prefabs of gameobjects of trees, rocks and mainly LAKES, where I have attached a script for triggering my fishing minigame (image). This script contains references to other game objects (interact window, timer etc.). Is there a way on how to "instantiate" (dont know how to use this word properly :D, so basically just fill) those references everytime the prefab of each lake spawns? I would appreciate any help.

dense rock
dense rock
dense rock
trim schooner
dense rock
#

true but I observed a couple of times where it then did not instantiate the go correctly on the next start. There then was an object with the same name without any components

#

that error has since been gone tho

glacial snow
#

how difficult is implementing steering behaviours for AI pathfinding thinker
like this where you have different weights for which direction the AI might want to go

clever lagoon
#

NOTE: if this problem is occuring whe you say.. change scenes- my suggestion wont help. only good for quitting.

static matrix
chrome berry
dense rock
#

thats a good one

dense rock
marble mauve
#

Hi. I have created my first unity protect. I don't have lot of knowledge in unity but I know C#. How can I split the camera into two parts and assign a different background color to each part.

chrome berry
marble mauve
#

I don't know if I have to create and script that implements the feature or in the other hand there is a way to do that without using c#

chrome berry
marble mauve
lean sail
# glacial snow how difficult is implementing steering behaviours for AI pathfinding <a:thinker:...

The hardest part is actually getting the data for what is a valid path. You could just use unitys navmesh for this. The pathfinding algorithms are already invented, you just need to choose one.
If you're talking about doing this solely based on raycast (which is what your image looks like) then that isnt pathfinding because it's just going in the direction of least resistance and hoping there isnt some giant wall it isnt aware of

chrome berry
#

Or a large sprite that's just a single colour

marble mauve
#

and where I find a flat plane. Sorry but as I said I don't know so much about unity. I am testing and then I will start reading the guide and docs. It could be a canvas in component > layout ?

chrome berry
marble mauve
#

2d

chrome berry
#

Create a square PNG in the art package of your choice (i.e. GIMP) of the right colour. Dump that into your scene as a sprite and stretch it to the right size as your background.

marble mauve
#

so I have to create a PNG which will be my background? and then add it as an script an resize it with the dimensions of the camera?

chrome berry
terse surge
#

there was a thing idk whats its called but like certain type of code. My teacher suggested for us to look into it as it would help us with a problem someone had, where basically they wanted to close whatever UI menu was open if another one gets opened, anyone knows what im talking about here?

marble mauve
chrome berry
#

Then whatever other sprites you have will just be above that background sprite

marble mauve
#

Okey. Thanks.

chrome berry
#

Or, if you're doing everything in UI only, with no sprites, then you'd place Images in your Canvas as the background, and stretch those to fill the canvas and colour them

proud loom
#

I want to learn how to use unity and code different things but I’m unsure how to learn the code that is used for making games

tawny elkBOT
#

:teacher: Unity Learn β†—

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

marble mauve
sacred sinew
#

I have a game object that appear on the "scene" but not in the "game" tab, it uses a code to move with the mouse but does not show on the game render, do someone know why ?

hexed pecan
#

Is it a 2D game? If yes, just set worldPos.z to zero

#

IIRC ScreenToWorldPoint gives you a position on the camera's near clip plane

sacred sinew
#

ok thanks

#

it worked thx

dark kindle
#

what would be a good workaround to this issue, "size of the vertical scrollbar reverts back to 0.61 when trying to adjust the value slider"

#

I am dealing with this problem where i have multipple buttons

#

inside scroll view and i cannot see all of them

heady iris
#

that issue is about the scrollbar itself

#

it sounds like your problem is about the contents of the scroll rect

dark kindle
#

yes, and i ask here because maybe there is a programmatic solusion

heady iris
#

Did you use the "Scroll View" preset?

dark kindle
#

let me confirm

#

yes

heady iris
#

put a ContentSizeFitter onto the "Content" object

#

Also put a VerticalLayoutGroup onto the "Content" object. Check both "Control child size" boxes and uncheck "force expand"

#

You will now need to put a layout group onto every object that has children.

#
  • Content <-- ContentSizeFitter, VerticalLayoutGroup
    • ButtonParent <-- VerticalLayoutGroup
      • Text
    • ButtParent <-- VerticalLayoutGroup
      • Image <-- VerticalLayoutGroup
        • Text
#

e.g.

#

All of them should be set to control child size.

#

(i'm getting back to work and won't be around for a bit)

dark kindle
#

ok appologies, and thank

woven horizon
#

I am trying to make the bullet trail for the weapon disappear after the certain time has passed

#

the idea is to simulate what would be a gameobject projectile while I am just using raycasts

#

I am trying multiple approachs but cant seem to find one that works

latent latch
#

why dont you just use a linerenderer

woven horizon
#

it is a gameobject with a line renderer

#

and nothing else

latent latch
#

so, what's the exact problem? You can set the time which each segment expires.

woven horizon
#

wait you can do that

#

omg

latent latch
#

there's a curve right on it

#

go play around with it in the inspector

woven horizon
#

can I dynamically adjust it tho?

latent latch
#

uh, it may use keypoints

woven horizon
#

cause the problem I have is that I want it to disappear depending on how long it would have taken a gameobject to hit whatever was hit

#

and then run all the logic after that time has passed

#

or should I instead have no bullet trail and just show a muzzle flash and an effect where the bullet hit?

#

I think that's a better idea and I am just making it harder for myself

latent latch
#

Has a time property

woven horizon
#

oh ok

#

thats very helpful

#

thanks

marble mauve
#

I am doing a canvas but I can't reduce the width or the height and I can't move it through the screen

soft shard
# terse surge there was a thing idk whats its called but like certain type of code. My teacher...

Not sure if there is a particular word for it, sounds like your describing just updating a reference, or possibly a event bus could also handle something like that, or possibly a state machine, though those approaches are usually a bit more involved than your description, it sounds like your more-or-less asking about something like this?

public class SomeUI : Mono
{
GameObject opened; //keep a reference to what is opened

public void OpenAnother(GameObject ui)
{
//should probably do a null-check incase nothing is opened
opened?.SetActive(false); //hide the previous window
opened = ui;
opened.SetActive(true); //show another window
}
}

In that example, something would call OpenAnother passing the UI object that should be displayed, causing the current one to close, get updated and show the one passed instead, though im not 100% certain if this is what you were trying to describe

soft shard
# marble mauve I am doing a canvas but I can't reduce the width or the height and I can't move ...

The canvas has 3 modes, by default it is locked to the screen space overlay, meaning it will render above everything and cannot be adjusted through the transform, instead it uses a Canvas Scaler to adjust itself based on the screen its displayed on: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UICanvas.html

If you want to be able to change the size of the canvas itself, you may want to try one of the other 2 modes, however that also means it wont properly overlay and fit the screen, so its good for in-world UI but not UI you might want always on screen

marble mauve
#

I'm trying to resize it because I want it to fit with the camera

marble mauve
#

Also I'm trying to change the button text of a button in that canvas but there is nothing in the inspector that might be consider to change the button's text

soft shard
mighty flax
#

Apparently my question should be asked here instead of #πŸ’»β”ƒcode-beginner -

Hi everyone! I need help with a terrain generation script that I tried modifying to work multi-threaded using Burst and NativeArrays/Lists. The game I'm working on is meant to feature a minecraft-esque terrain and I had it working single-threaded and using a LOD system that just lowers the resolution of the voxels the further away you are from them on orders of magnitutes of 2. This was all working on a single thread but was obviously very laggy when you moved between chunks because all the processing was happening on the main thread. I've programmed what I believe should be the multi-threaded equivalent of the previous code I had written but now nothing renders and additionally I've got an error along the lines of "Leak Detected: Persistent Allocates 1 individual allocations." which I'm not entirely sure how to fix because I need this array to stay persistent

soft shard
marble mauve
sinful mortar
#

is there a way to tell which monobehavior this was? as in a string name or something

woven horizon
rigid island
sinful mortar
#

I guess just gotta dig into the yaml

latent latch
woven horizon
hexed pecan
rigid island
sinful mortar
#

yeah exactly, question was figuring out which file that was, but looks like I just have to redo this because it's related to UI Toolkit being updated between 2020 and 2021

hexed pecan
sinful mortar
#

so I ended up removing them and yolo guessing based on the script and kinda got it working πŸ˜…

nimble cairn
#

Thoughts:

When a player turns sound effects volume to 0 it is inefficient to keep audio sources enabled in the scene.

rigid island
nimble cairn
#

This is not an issue I am currently facing. I just wanted to open a dialogue.

rigid island
nimble cairn
#

Well, I am speculating that it would be more efficient to disable all sound effect audiosources.

Someone else might subscribe to another school of thought. I can already hear someone saying it's a micro optimization.

long ridge
#

How do you update navmeshsurface via script?

rigid island
#

call bake

#

done