#archived-code-general

1 messages · Page 24 of 1

thick socket
#

normally I use it the other way

#

however in this rare case I need to see if it has a value

rain minnow
#

if the value is in the dict, then it has a key . . .

#

you're just comparing the wrong thing, that's all . . .

thick socket
#

right, there isn't a dict.ContainsValue() iirc

lucid valley
#

there is .ContainsValue()

thick socket
#

wat

#

wow

lucid valley
#

worse performance than a key check

thick socket
#

been googling for like 20m 😭

#

thanks

rain minnow
lucid valley
#

doesnt give the key, if you need that as well then you'd need do the ContainsValue manually

rain minnow
woeful leaf
#

(google1google2google3)

thick socket
#

I was googling the actual question and not just dictionary c# which was the issue

rain minnow
#

always google what type or class you are using. you'll get the actual link to the class (type) and all of its members . . .

simple egret
#

If you're going to use it backwards more, you can make two dictionaries with the key-value pairs swapped and act on both at the same time

thick socket
#

good to know thanks

#

I think I'll stay with my foreach loop...just have to store the values I want to change and wait until Im outside the loop to modify the dictionary

#

hmm

#

I wonder if I just throw a break if it wont be mad at me (it was mad at my modifying EquippedList while doing foreach on it)

#
    foreach (var items in EquippedList)
        {
            if(items.Value == item)
            {
                tmpList.Add(item);
                EquippedList[items.Key] = null;
                break;
            }
        }
#

if I have a break here it will break the loop and not the if statement right?

simple egret
#

break only acts on loop constructs, so yeah

#

Depending on your code editor if you click on break to put the editing cursor on it, it'll also highlight the loop it acts on

#

(VS22, was also the case for VS19)

lucid valley
rain minnow
thick socket
#

that makes sense

#

for some reason I thought using continues like that was bad practice or something

simple egret
#

I find the version with continue way less readable

#

Adds complexity on where the execution flows

lucid valley
#

i'm the opposite lol

rain minnow
thick socket
#

fair enough

#

is there any way that when the game is running and you change code everything doesn't break and you have to re-click play?

#

I assume not but figure I ask 😄

lucid valley
#

nope, Unity doesnt support hot reload

wicked river
#

Hey! I am having a world of trouble spawning an equipped weapon|item into the characters hand at the correct orientation and position. I would love some advice on the topic please.

I have tried setting a weapon slot empty gameObject in the palm of the player as well as setting an empty gameObject on the grip of the weapon to perhaps attach it that way but I can't seem to get the rotation right and I really don't want to using hardcoded values as I will have more than one weapon and some are 2 handed as well.

wicked river
#

3D sorry

thick socket
#

unfortunate, I could kind of help you if it was 2d lol

wicked river
#

All good

wary ferry
#

I have a tile map collider on a tile map made out of rule tiles. Somehow I set it so only the tiles on the edge got the collider and I can't figure out how, does anyone know what setting this is?

#

like this

leaden ice
obtuse canyon
#

How can i detect a change in value.
For example a character is set to lerp to an object and i want an animation play only when he is moving

wicked river
leaden ice
wicked river
#

ah, like this I assume

leaden ice
#

sure

wicked river
#

so the position and or rotation is dependend on in my case where I put the WeaponSlot. I need to just play with the empty gameObject to find the right position in the palm and right rotation

wicked river
#

🥳 Thank you .

proven plume
thick socket
#
tryBackButton = root.Q<Button>("tryBackButton");
        if (tryBackButton == null)
        {
            Debug.Log("backbutton null");
        }
        tryBackButton.clicked += GoBack;
``````cs
void GoBack()
    {
        //MainMenu.instance.CloseMe(root);
        root.pickingMode = PickingMode.Ignore;
        root.style.display = DisplayStyle.None;
        Debug.Log("backclicked");
    }```
#

am I missing something obvious here?

#

the button isn't clicking/doing the GoBack

rain minnow
#

just call/invoke the event manually . . .

rain minnow
thick socket
#

so yes, atm its not clicking

#

not sure if I set something up wrong or wacky type or ui toolkit being dumb

rain minnow
thick socket
#

I have a debug to see if its null(its not) then another debug for the event that fires when its clicked

orchid bane
#

What is the purpose of using Strategy pattern instead of simply using implementers of the corresponding interface? In other words, why create the Context class?

thick socket
#

figured it out anyway, stupid UI toolkit stuff

proven plume
#

If you want to manually trigger the even on a specific UI element and you have the reference, you can invoke that directly (the exact call will depend on what event and ui type you are using). If you want a general way to fake input and mimic what the event system is doing, what you found on google is correct but would take a bit more setup. It's how input modules work.

wispy wolf
#

I have an object that I want to move in a spiral pattern outward while maintaining the same linear speed. How would I approach this?

woeful leaf
#

Math

brisk otter
#

Can someone explain to me why local variables are useful? Isn't it always going to me more efficient for the computer to declare them as regular fields?

woeful leaf
brisk otter
#

i feel like they just encourage lazy coding

woeful leaf
#

And you’d also have to manually reset the non-local variable

#

And even if there is a performance difference, it’s practically non-existent

brisk otter
woeful leaf
#

Unless you keep doing a GetComponent and store that in a local or smth then it is

woeful leaf
brisk otter
woeful leaf
woeful leaf
#

Which is why it’s good for for loops

brisk otter
#

Im just thinking, cause each time you create a local var in the update function, you are really allocating and deallocating memory every frame, when you could have just allocated it once when the program started and ended

brisk otter
woeful leaf
#

I’d google1 google2 google3

#

If you want to know more

rain minnow
brisk otter
#

I think i had a bit of a misunderstanding about how local vars worked

#

it makes sense more now

rain minnow
#

it's smarter to declare the local variable outside of the loop instead of inside though. no need to create it every iteration . . .

rain minnow
brisk otter
#

got it

#

thanks so much!

rain minnow
#

sorry, forgot about this. the second parameter must derive from BaseEventData but you supplied a DragEnterEvent type as the argument. if you don't need to pass any data then use null . . .

cedar pivot
#

How can I know in advance where the ball will land?

#

where will it touch the ground

prisma birch
#

How can I set the rotation of the scene view camera manually? Like I would like to set the euler angles directly rather than free rotating?

#

I managed to select the scene camera but it looks like none of the properties are editable

proven plume
# cedar pivot How can I know in advance where the ball will land?

assuming drag is turned off so that horizontal velocity is constant, projectile motion equations can calculate that. A simple case is straight forward but terrain with uneven height would make that more challenging since you would need to know where the projected arc intersects with a solid object at an arbitrary height.

ionic yew
#

like in code? or in the UI

prisma birch
#

Either, I just want to set the euler angles to something specific

cedar pivot
#

Thx

steady moat
azure crescent
#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed = 5f;
    public float jumpForce = 10f;
    public float wallJumpForce = 10f;
    public float wallStickTime = 0.5f;
    public LayerMask wallLayer;

    private Rigidbody2D rb;
    private bool canJump;
    private bool canWallJump;
    private bool isSticking;
    private float stickTime;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Space) && canJump)
        {
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
            canJump = false;
        }

        if (Input.GetKey(KeyCode.Space) && canWallJump)
        {
            rb.AddForce(new Vector2(wallJumpForce, jumpForce), ForceMode2D.Impulse);
            canWallJump = false;
        }

        if (Input.GetKey(KeyCode.Space) && isSticking)
        {
            stickTime += Time.deltaTime;
            if (stickTime >= wallStickTime)
            {
                isSticking = false;
            }
        }
        else
        {
            stickTime = 0f;
            isSticking = false;
        }
    }

    void FixedUpdate()
    {
        float moveX = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveX * speed, rb.velocity.y);

        if (rb.velocity.x != 0)
        {
            speed += 0.01f;
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            canJump = true;
        }

        if (collision.gameObject.CompareTag("Wall"))
        {
            canWallJump = true;
            isSticking = true;
        }
    }
#

so i have this code when i try to add it to my empty i get a text box saying...

steady moat
#

The script and your class does not share the same name

#

One is called playercontoler while the other is called PlayerController

vagrant agate
#

Also float moveX = Input.GetAxis("Horizontal"); inside of Fixed Update can have undesirable results.

azure crescent
steady moat
#

I mean, there is a lot that is wrong with this code. He is going to figure it out.

azure crescent
steady moat
#

You don't need to make anything in the FixedUpdate.

vagrant agate
#

You should always check input in Update not fixed update

#

And just another tid bit of info. Look into how to use enums instead of all your booleans for player state. It will untangle spaghetti boolean logic

steady moat
#

StateMachine is a most for a controller

steep scarab
#

Does anyone know how to refer to the trees of my terrain via script? I currently have a script getting a navmesh agent to take cover at positions working and I want to add the positions of all the trees on my terrain to a kd tree.

vagrant agate
azure crescent
vagrant agate
#

The general rule of thumb, is player input is detected in update not Fixed(because of the fixed framerate) And dealing with force/rigidbody is added in Fixed Update mainly for fast moving objects.

vagrant agate
#

I believe the main reason is using Update instead of Fixed Update for fast moving objects can crap out at very high speeds. I'm not saying that is the case here. But getting in this habit isn't a bad idea.

azure crescent
#

better?

viral marlin
#

I'm using resharpner and everything works mostly fine a part from autocompleting unity's inbuilt functions, e.g onCollisionEnter shows but when I try to autocomplete it I just get onCollisionEnter and nothing else while without resharpner it autocomplatets it with whatever is needed. I am also using visual studio

vagrant agate
jagged pilot
#

Hi everyone, I'm making progress on my hidden character game and the next pattern I need to create is making all of them bounce off the sides of the camera/screen/game area. I have a game reference as MP4.
And here is a generic reference of a bouncing DVD logo screensaver:
https://www.youtube.com/watch?v=5mGuCdlCcNM&ab_channel=RaúlBlanco
I don't believe there is any difference in behavior between the game reference and the generic reference.

I have a script that can instantiate all the characters onto a grid and give them their own unique direction and speed to transform. I think that to produce this pattern, I need use the cross product to get a vector perpendicular to the original vector of the character and the side of the game area, then replace the character's vector with the perpendicular vector. Then we just need to repeat it every time the character runs into a side of the game area right?

If it hits a corner, what vector should be used? I'm unsure about that.

Bouncing DVD Logo screensaver for modern screens (4K 60fps 16:9) - 10 hours NO LOOP

▶ Play video
vagrant agate
#
public class Player : MonoBehaviour
{
    private Rigidbody2D _rigidbody2D;
    private bool _isGrounded;
    private bool _jump;
    private float _jumpForce;

    private void Update()
    {
        if (Input.GetButtonDown("Jump") && _isGrounded)
        {
            _jump = true;
        }
    }

    private void FixedUpdate()
    {
        ApplyJumpForce();
    }

    private void ApplyJumpForce()
    {
        if (!_jump) return;
        _jump = false;
        _isGrounded = false;
        _rigidbody2D.AddForce(new Vector2(0f, _jumpForce), ForceMode2D.Impulse);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            _isGrounded = true;
        }
    }
}

Take the concept, not the best code. @azure crescent

vagrant agate
vague tundra
placid ridge
#

Hi! I'm trying to goto a position, but i want to be stopped by colliders along the way, like the example image. Is there any way i can do that?

vague tundra
placid ridge
ancient cloak
#

and you know its instantaneous velocity

placid ridge
jagged pilot
jagged pilot
azure crescent
viral marlin
warm rose
#

Why can't I jump in unity
First person 3D
I followed a tutorial because I couldn't get it to work
But it still doesn't work
Idk if its just my computer
Could someone please help

viral marlin
#

and then hav ethe player go whereever the raycast hit

ancient cloak
viral marlin
#

yeah

placid ridge
#

k

viral marlin
#

I'm not to sure how to do it myself but I do know it is possible

warm rose
#

Couldn't fit on discord so here

ancient cloak
#

good boy

#

just use the keycode. also IMO you should use rigidbody.addforce with ForceMode.Impulse

#

ALSO

#

does that even compile?

warm rose
#

Yeah

#

It let me enter playmode without any errors

viral marlin
#

have you tried making the radius larger?

ancient cloak
#

no shot

ancient cloak
ancient cloak
#

tell me why its there

polar marten
ancient cloak
#

this suit is black NOT

polar marten
#

"i make joke!"

#

"this character is grounded, pause, not"

vague tundra
# placid ridge Yes.

I'm struggling with a similar problem - controller my character such that it can respect collisions

You could manually control the objects velocity and then sit it to 0 when ur not moving.

What I'm trying currently is to use a CharacterController component on my player. It lets you perform a Move that will stop when it hits collisions

viral marlin
ancient cloak
#

ugh yall drive me crazy

viral marlin
#

😛

viral marlin
ancient cloak
#

can yall just let me be right

#

the exclamation mark is only a negation when a value follows it. when a value precedes it, it has another function, one i know you didn't intend

polar marten
#

the null forgiving operator came out after brackey's though

ancient cloak
#

stands to reason that it's incorrect

viral marlin
#

you are right

#

the test I did was actually really dumb

warm rose
#

So what should I change to make my player be able to jump?

viral marlin
#

I just saw that 🙃

polar marten
#

did you know typescript and csharp are designed by the same person?

viral marlin
#

as at the end it doesn't really do anything

ancient cloak
#

have you debugged to see if the jump section of code is being hit? here

warm rose
ancient cloak
#

either put a breakpoint and step through to see what's happening or put debug logs to confirm what you think is happening is actually happening

warm rose
#

It's not being detected

ancient cloak
#

if literally nothing is happening then press play. you should be able to debug your code

#

what values are you logging?

#

and where are you logging them

warm rose
#

This If statement

#

To see if its detecting my jump

ancient cloak
#

okay

#

try replacing "Jump" with Keycode.Space

#

using string literals for input detection is cringe

cosmic rain
#

Did we already confirm that isGrounded is true?

ancient cloak
#

^ could log it

warm rose
#

I gtg now, Ill see later

#

Thanks for helping

steep scarab
#

anyone know of a good kdTree script I can yoink?

steep scarab
#

ty ty

wild nebula
#

Its in DOTS Plus asset's collection library

#

Been loving it, can be used in gameobject too

#

Never regretted getting it!

vague tundra
#

Is inheriting from Monobehaviour the thing that allows you to create instances of a class?

rain minnow
vague tundra
#

So a class that derives from nothing cannot?

dusky spear
#

If I wanted to write a custom lighting system for a 2d sidescroller, what system would I want to use for that

#

I already know how I’d calculate the shape of the light, I just don’t know how I would go about getting it into the level as actual light

#

My original idea was just to use Freeform light2ds and have the script change the light shape but after some quick forums scrolling I have come to the come to the conclusion that that is not possible

#

What would you guys recommend

#

Btw this would need to be capable of updating dynamically

#

How do I go from a list of vertices of a shape in a script to the level being lit in that shape

#

Just being able to set the shape of Freeform light 2d would work for me so if anybody knows a way for that to be possible dynamically that would work great

neat lagoon
#

but understand that creating an instance of a class and attaching to a gameobject are very different things

#

one is fundamental to C# and another is just some random Unity functionality

vague tundra
#

I see, I see

#

How can I provide a scriptable object with a reference to a class/script?

#

The class/script is not an instance

full scaffold
#

I would assume just the name of the class

dusky spear
full scaffold
#

Create many many many... ray casts

dusky spear
#

Nononononono I know how to actually do the calculations

#

Once I have the list of vertices that make up the shape of the light

#

How to I get it to actually display as a light ingame

full scaffold
#

Mesh renderer

dusky spear
#

Kinda like a Freeform light2d, but something able to be updated thru a script

full scaffold
#

I mean you can use like a shader or something

dusky spear
#

I wish the Freeform light 2d just let you set the light shape in the script

vague tundra
#

How can I get a reference to a non-instanced script on an instance of a scriptable object?

cosmic rain
vague tundra
#

I'm not sure how to correctly refer to it...
A script that I dont need to put on any specific game object.

#

But I want a reference to the script from instances of my scriptable objects

cosmic rain
#

A plain C# class you mean? Not inheriting from MonoBehaviour or ScriptableObject?

vague tundra
#

I guess that is exactly what I'm getting at, yeah

#

But I only want it accessed by the scriptable objects i give it to

cosmic rain
#

Well, you can access it the same way as any other class field. Make it public(don't), expose it with a property or a getter method.

cosmic rain
#

If you only want it accessible in the class it's declared in, then just make it private🤷‍♂️

vague tundra
#

Mmm, I wish my brain was larger so I could accurately explain what I was after...

Let me come at this from another angle

What are the requirements for something to accepted into this slot:

cosmic rain
#

It needs to be a serialized reference by unity(probably wrong wording). Basically, it needs to inherit from MonoBehaviour or ScriptableObject.

vague tundra
#

I see, hmm

rare tendon
#

can someone help me with an audio issue? im trying to detect the audio level from the main microphone, but unity doesnt have a built in way of doing this. i found this: https://forum.unity.com/threads/check-current-microphone-input-volume.133501/ but when i try it the output doesnt actually correspond to how loud my voice is. My code:

private static float LevelMax(AudioClip clip, int window)
    {
        float levelMax = 0;

        //get the position to start checking from, which is a window starting from current pos and extending backward by 'window'
        var micPosition = Microphone.GetPosition(null)-(window+1);
        
        if (micPosition < 0) return 0;//if we dont have sufficient data yet, return 
        
        var waveData = new float[window];//array of floats representing the waveform of the captured window
        clip.GetData(waveData, micPosition);//populate wave data with data from the audio clip
        
        // Getting a peak on the last 'window' samples
        for (var i = 0; i < window; i++) 
        {
            var wavePeak = waveData[i] * waveData[i];
            
            if (levelMax < wavePeak) 
            {
                levelMax = wavePeak;
            }
        }
        return levelMax;
    }```
This is being called in Update(), and it just returns a random float around 0.0025, with no bearing on the volume of my room
cosmic rain
vague tundra
#

So in my setup, Wooden Sword (Equipment) is a ScriptableObject. (An instance of a scriptable object i think would be correct to say).

I want Ability to be a class that contains a single method.

I want to be able to give different Equipments the same Ability, doing so thru the inspector

cosmic rain
vague tundra
#

Wonderful, thank you. That makes sense!

#

Oh, wait. Frick

#

How would I implement a different method for each Ability?

#

This is kind of the code setup I'd be looking at. ExampleAbilitySwordSwing is not being accepted into the highlighted slot in the previous picture

leaden ice
#

You'd have to create an asset from the SO and drag that

vague tundra
#

I see, cool. So for every ability, I'd have only 1 corresponding SO?
Is that a good way to do it?

halcyon nimbus
#

Ahh, a perfect conversation. I was just about to come in and ask about how people would implement something like the keywords on magic the gathering cards.

cosmic rain
halcyon nimbus
#

what are the alternatives?

cosmic rain
#

Hardcode it.

halcyon nimbus
#

where?

#

its hardcoded into the SO isnt it

vague tundra
#

Mmm... I think SO's are the wrong thing to use for me here.
I'd be creating 100 scripts that inherit from Ability, then adding CreateAssetMenu to them all, but then only ever creating 1 SO per script. mmm

vague tundra
halcyon nimbus
#

Really I want to do something a little different, but that is the closest I can get to explaining it with what I know

vague tundra
#

Lmk if you get a good solution(:

halcyon nimbus
#

for mtg, there are lots of reused effects and it would be nice to be able to reuse them in the edittor as well rather than hardcoding the same thing onto different cards

void basalt
#

Is there a good way of disabling an object's visual rendering, but still display shadows?

vague tundra
#

Yeah righto I reckon that sounds like what I'm after actually

#

I want abilities than can be given to weapons that can be equipped by the player, allowing player to use the abilities

broken light
#

any one know how to correctly rotate an object for the rotation handle in unity?

#

for me it goes way too fast

#

im not sure how to correctly use the quaternions to fix it

#

this is my code:

var q = Quaternion.LookRotation(Vector3.forward, Vector3.up);
var forward = Handles.RotationHandle(q, data.Position) * data.Forward;
data.Forward = forward;
#

not sure why its so damn crazy fast for such a small amount of rotation - how do you fix it?

#

ah i fixed it

vague tundra
broken light
#

no i was using the wrong forward to multiply the rotation

lethal plank
#

hmm where should i ask about animation rigging?

lethal plank
#

lemme try

swift falcon
#

maybe its a stupid question, but how do I put a gameobject on top of the cursor? In a position that the camera first sees that gameobject and behind it its the cursor. I am trying it but it seems that the cursor always stays on top.

plucky inlet
#

Either let each door side check with a raycast or stop movement when a collision happens? sth like that

swift falcon
#

and If I do Cursor.visible = false, the cursor its still in front

plucky inlet
swift falcon
#

I dont want to disable it, just hide it in front of a sprite. I dont know if Im explaining it right, sry for my english. Something like take the Z coordinate of the cursor and put my gameobject in front of that, in a 2d game. But It doesnt seem to work.

plucky inlet
#

If its the hardware cursor, it is ALWAYS on top of everything unless you make it non visible. But if you have a custom sprite attached to your mouseposition, you could offset that in the layer depth. So, what cursor are you using?

swift falcon
plucky inlet
#

And if your cursor is always visible, even if you set it to false, that is somehow weird. Did you test that in build? Just to be sure its no editor limitation

grizzled trail
#

I've got a question about building from the command line for macOS. In the build window you can select macOS for the target platform, and Intel 64-bit + Apple Silicon for the architecture. What's the equivalent of setting these in the command line? The docs say -buildTarget OSXUniversal and -buildOSXUniversalPlayer respectfully but I don't seem to get anything built, and my logs don't show an obvious error. I unfortunately can't share the logs, but anything to look for / go off would be really useful.

grizzled trail
#

🧐

plucky inlet
#

It was build setting wise, not sure it helps you in command line. I can post again

// It is not visible in any of the managed assemblies, you will never, ever find this
#if UNITY_EDITOR && UNITY_STANDALONE_OSX
// Intel amd64:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.x64;
// Apple Silicon/M1 ARM64:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.ARM64;
// macOS Universal or Fat binary:
UnityEditor.OSXStandalone.UserBuildSettings.architecture = UnityEditor.OSXStandalone.MacOSArchitecture.x64ARM64;
#endif
#

Did you try ARM64 ?

grizzled trail
#

ARM64 isn't an option according to the unity docs under build arguments

#

https://docs.unity3d.com/2022.2/Documentation/Manual/EditorCommandLineArguments.html

This is the command I use (or rather that teamcity generated, but that i've verified doesn't work running it manually.)

"C:\Program Files\Unity\Hub\Editor\2022.2.2f1\Editor\Unity.exe" -batchmode -projectPath "/my-app-name Project/" -buildTarget OSXUniversal -buildOSX64Player D:\Builds\my-app-name\App\Builds\54_develop_20230126_10391194\MacOS\my-app-name.app -executeMethod Editor.BuildScripts.BuildComponents.TeamCity_PrepBuild_Development -versionFile "C:\BuildAgent\tools/Development MacOS_version.json" -quit -logFile D:\BuildAgent\temp\agentTmp\unityBuildLog-9300905772748481244.txt

#

The windows equivalent works fine

plucky inlet
#

and the universal thing does not output anything?

grizzled trail
plucky inlet
#

Is it correct to use buildTarget AND buildOSXUniversalPlayer ?

grizzled trail
plucky inlet
#

Did you try with only -buildOSXUniversalPlayer ? Just guessing here while googling 😄

#

Oh wait, you are trying to build for mac on a windows machine?

swift falcon
#

How to properly destroy a DDOL GameObejct from another script? I thought Destroy(Class.gameObject) would do it but it gives me a NullReferenceException

plucky inlet
swift falcon
plucky inlet
#

Otherwise its not a singleton as what you would DDOL use for

swift falcon
#

It's private static at the moment

plucky inlet
#

public static and then Class.instance.gameObject can be destroy

swift falcon
#

Great thanks

plucky inlet
grizzled trail
plucky inlet
grizzled trail
#

You can build for everything, I've done it, verified it works

#

Even have it running on our dev mac

plucky inlet
#

yeah, a m1 mac is good at emulating standard intel mac builds

grizzled trail
#

Command line will just not write a binary

grizzled trail
plucky inlet
#

Okay, then this is either lacking Unity who are behind of command line tools or we are missing some weird thing here 😄

glacial halo
#

Hi all,

I'm hoping someone can point me in the right direction on this as it's driving me nuts. lol.

I have a particle system which gets instantiated when a ball hits the walls of a tunnel (to 'simulate' a type of shield hit).

The problem I'm having is getting the particle system to 'align' with the geometry of the tunnel.

I have the system set to 'Local' space, but it keeps dinging up with random 'directions'.

Anyone have any ideas? 😕

`private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "ShieldWall")
{

        Debug.Log("Ball Impacted");
        Vector3 impactPoint = collision.contacts[0].point;
        Quaternion impactRotation = Quaternion.FromToRotation(Vector3.up, collision.contacts[0].normal);
        GameObject shieldHit = Instantiate(shieldParticle, impactPoint, impactRotation);

        Destroy(shieldHit, 1);
    }
}`
grizzled trail
#

Actually thinking about it yesterday I did an apple silicon only build and it built and ran fine

#

I'm leaning on the side of command line seriously lacking, but it should still output a binary.

#

The alternative is I just have build scripts for each build I want, load Unity in batch mode and run the build script. Kind of defeats what I'm going for but at least it might work

cosmic rain
glacial halo
#

This is what's happening when my car hits (using the car to test)

atomic wasp
glacial halo
#

Well, I just tried with a plane with material on it, and it works fine, so I'm just gonna go with that approach. lol.

atomic wasp
#

(if it has a nonconvex mesh collider)

unreal valley
#

Is using Reflection a bad way to save and load data?

slow crag
#

Does anyone know how I can capture the bounds (frustrum) of a 3d camera, so that I can set the ortographic size of another 2D camera to always be just large enough as what the player sees?
I've got this code from ChatGPT:

float perspectiveFov = main3DCamera.fieldOfView;
float aspectRatio = main3DCamera.aspect;

// Calculate the vertical size of the frustum at the camera's distance from the plane
float frustumHeight = 2.0f * Mathf.Tan(perspectiveFov * 0.5f * Mathf.Deg2Rad) * main3DCamera.transform.position.y;

// Divide by the aspect ratio to get the horizontal size of the frustum
float frustumWidth = frustumHeight * aspectRatio;

// Set the orthographic size of the lighting camera to half of the frustum width
lightingCamera.orthographicSize = -frustumWidth * 0.5f;

However, it only takes into consideration the zoom of the perspective camera. It also changes perspective (angle) by changing transform.rotation.x, so it can see more of the plane ahead of it, effectively going from top-down to 2.5D

Here's an example:

#

You can see that at a certain angle of camera rotation the lighting camera's orthographic size is too small so there is no lighting (shadows get lost)

steady moat
# unreal valley Is using Reflection a bad way to save and load data?

You could use reflection for saving data. If your save is small and not being made each frame, reflection wouldnt be an issue. In fact, most serialising library use reflection.

BUT, if you want clean code, you need to separate your saved data, from your game data.
BUT, if you are saving large word, reflection could add a decent amount of time.

You could use partial class to generate save procedure in each class and use BinaryStream.
You could use System.Reflection.Emit, which is faster but would be harder to implement.
You could, and should, use 1st/3rd party library for saving data. (JsonUtility)

unreal valley
#

I have EzSave but I just didn't feel like implementing it because my game is also Networked. I want the capability of saving locally and also sending to the cloud

steady moat
#

Which only implies manipulating the resulting files and has no impact on the save data itself.

proud juniper
#

Have a Quaternion question. Let's say I want to rotate a gameobject like a spaceship that may have it's Y axis not pointing up. If it's rolled onto its side and I'm in it and want to turn to the right... how could I manipulate a Quat to do this? I tried just doing transform.TransformDirection(0, 1, 0) (for yaw) and then doing Euler off of that and multiplying the existing rotation by the new rotation, but it is not working as intended

#

goal is a 6 degrees of freedom control, kind of like in the game Descent, X4, really any space game that lets you roll your ship

#

basically i want Euler() to take into account the existing rotation

#

nvm, I think it was working all along. sigh

#
    transform.rotation *= incrementalRotation;```

turnVec is from mouse input
thin aurora
#

Makes me wonder if you understand what the code does at all

steady moat
main shuttle
plucky inlet
#

Is it possible to get params for lets say transform as an enum, so rotation, position, scale? Or should I just do my own switchcase with a custom enum. I want an animation scriptable object, that can actually select, what I want to modify on the gameobject I put it on

#

I guess easiest way is to just get my own enum here

devout nimbus
#

Why would you need it as an enum?

#

Can't you use if(transform.position.x == i) and such?

plucky inlet
golden vessel
#

Hey, I'm struggling to find to make a container fit my text (tmp). I found text.bounds which seems to work, although sometimes the results isn't perfect, larger than needed. Is there any other easy to set up way to do it?

golden vessel
#

Ignore the bubble behind, i only set the bounds of the text here

unreal valley
#

So you are trying to make the bubble fit the text?

golden vessel
#

Yeah basically

sage charm
#

hey can i ask questions regarding photon here?

sage charm
#

ok thansk

golden vessel
#

The solution would be code but sure whatever

plucky inlet
golden vessel
plucky inlet
golden vessel
#

I'm setting the string of the text through script

unreal valley
#

I think you would have to child the bubble to the text and set it to expand. I believe

plucky inlet
#

Then the bubble is above the text

#

UI Text fit dynamically

next seal
#

Why cant I use ScriptableObject.CreateInstance with a custom type SO ? It just says that it cant be converted from CustomSO to unityengine.SO

#

🤔

#

oh its because my class doesnt derive from SO

leaden ice
#

Good chat

craggy nova
#
Debug.Log(Physics.Raycast(landingRay));```
why might this return false when the object is above a cube with a collider?
#

It probably is a stupid thing that I keep missing

daring cove
#

Hey,

How can I get the current renderer in an LOD Group?

// truncated
public GameObject tree;
// truncated

MeshRenderer meshRenderer = null;
LODGroup lodGroup = tree.GetComponent<LODGroup>();
autumn cipher
#

is it possible to access a gameobject inside the prefab from the scriptable object?

leaden ice
leaden ice
autumn cipher
#

maybe I can just do GameObject.Find() or something

craggy nova
leaden ice
craggy nova
#

I know what it is. But you need 2 points to draw a line don't you?

leaden ice
#

Yes and?

#

What's your object this script is attached to

#

Is it a capsule?

craggy nova
#

yes

leaden ice
#

By default Unity capsules have a height of 2

#

And pivot in the center

#

Meaning a ray with length 1 won't clear the size of the capsule

craggy nova
#

I extended it to 100 units before answering

leaden ice
#

Make your ray longer or start it from a point lower down

leaden ice
craggy nova
#

Ray landingRay = new Ray(transform.position, Vector3.down * 100);

leaden ice
#

Ok good

#

This still doesn't work?

#

Show the scene setup and the inspector of the box/cube if not

craggy nova
hasty canopy
#

Just a stupid dumb question, wouldn't the ray hit player itself if there's no layermask query UnityChanThink

leaden ice
#

For Raycast there's a separate parameter for length of the ray

#

It does default to infinity though

craggy nova
leaden ice
leaden ice
#

In this one it is.

hasty canopy
leaden ice
#

For Debug.DrawRay the length of the ray matters for example

craggy nova
#

scene is just this

#

well, the box is just a box honestly as a place holder for ground there is nothing specific about it

#

was I supposed to just send links of the pics?

#

as for layers, everything should collide with everything

#

player is an empty object at (0, 0, 0) position and the capsule collider is a component of the cylinder which is a child of the player

leaden ice
#

is the raycast starting inside the box?

craggy nova
#

the box is at -.5 with the y scale =1

leaden ice
#

put it lower

craggy nova
leaden ice
#

that may have the raycast starting slightly inside the box

craggy nova
#

fck

#

thank you

#

that was the problem

daring cove
#

Hi,

Why does it seem like that static batching is not working?

leaden ice
daring cove
leaden ice
#

you have to do it in the scene at edit time

#

it's the kind of thing that's baked in the editor

craggy nova
#

you can probably have 2 of the same object, one static one dynamic and use them interchangeably instead

#

I never used static batching so don't really know if there would be any point

daring cove
#

I'm optimizing terrain by putting every tree in a giant mesh and setting it to static, but it doesn't seem to work.

#

I'm still getting the same amount of draw calls.

next seal
#

I have the issue of this not working, not working as in I cannot type anything in the text field, this is an editor script and yes its in the editor folder, every other text field is working fine,

Is it just that you cannot store string temporarily in this function (which is OnGUI) and all the other text fields link to some otehr SO? If so how do I solve this

#

This is what it looks like right now, cannot type in this field

#

And then it also fails when I actually go and try to create the asset with the code you can see there, I thought maybe its because I am not giving it a name so I added that functionality, but idk why at this point

leaden ice
#

string newObjectName = "";

#

every time it renders the GUI it will make it empty

next seal
#

I thoguht im just decalring it in order to say well this is a variable, be prepared for it to come up

leaden ice
#

that's an actual string

next seal
#

T_T

#

Okay how would I change this

leaden ice
#

and you pass it in to populate the text field

#

store that string somewhere more permanent

#

in the Editor object itself or whatever serialized asset you're editing here

next seal
#

out side of OnGUI?

leaden ice
#

yes

next seal
#

should I already set it as = "";

#

or just

#

string newObjectName;

#

I got this rn

leaden ice
#

you'll want to initialize it yes

next seal
#

and then it gets populated with whatever I put into the text field?

#

wont it stay in the editor script forever then though? >_>

leaden ice
#

Only for the life of that variable, which is the life of whatever object this is

#

some editor

next seal
#

until i like manually delete it that is

#

because ideally i want it to be empty as soon as I hit the + button

leaden ice
#

try it

next seal
#

okay

leaden ice
next seal
#

Well I am still getting the error cant create object

leaden ice
#

what error is that

next seal
#

UnityException: Creating asset at path failed.
DialogueEditor.OnGUI () (at Assets/Scripts/Editor/DialogueEditor.cs:61)

leaden ice
#

print it out

next seal
#

Uhm yea one sec

leaden ice
#

probably that folder doesn't exist

next seal
#

yea

leaden ice
next seal
#

its trying to find a folder that would really be an asset

#

OHHHH I KNOW WHY

#

the way i get the path is

#

"Just take the path of the currenlty selected Object, and then just add the name.asset"

#

so thats why its wanky

#

But how can I get JUST the path and not the Test.Asset

#

Test is the currently active dialogue object

#

im edting that object in the editor basically

#

I cant very well be like "Get the path and then remove the last bit"

leaden ice
#

well you could but that's kinda hackyish

next seal
#

Can I somehow say "place it in the same folder as this file"

leaden ice
#

GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'

#

seems promising

next seal
#

I'll try that thank you

tough osprey
#

Is there a way to auto manage delegates based on an interface without constant scanning of objects and without explicit registration copy and pasted everywhere?

What I want is that when CustomHandler is created, it finds all objects that implement HandleMe and registers them (this can be a complete scan). Then all new Objects that implement HandleMe should then register themselves (this is the part I can't figure out without duplicating code).

class SomeObject : HandleMe {
    public void doWhenHandle() { }
}

class CustomeHandler {
    public delegate Handle;

    public void Awake() {
        \\ Find all existing objects that should be added
    }

    public void Update() {
        if (something) handle();
    }
}

For the registration of objects created after the fact, I could do something in their Awake method but I want to avoid having to code that every time. I thought about using default methods in the HandleMe interface but that would then hide the methods if the object wants to actually do something in Awake.

leaden ice
#

If it's being done from one place maybe you do the registration there?

#

or make the thing that creates them fire a static event

#

and CustomHandler listens for that event

next seal
#

Ohhh myy gooddd PraetorBlue youre the best, youre the MVP of this server, no matter who needs help you like always find the solution, thank you!

tough osprey
#

So the fun part is that I'm using Photon Fusion so it may be instantiated by Fusions Spawn functionality. There's Spawned() and AfterSpawned() methods that are similar to Awake, but I'm not sure if I have access to automatically do something on every Spawn.

halcyon nimbus
#

So its possible to serialize a class and create new instances of that class from the inspector. In the example below you would be able to populate the items array in the Shop class from the inspector.

[Serializable]
public class Item {
  public string name; 
  public string price;
}

public class Shop : Monobehaviour {
  public Item[] items;
}

But what if I wanted to to the same with various types? Is there a way I could make a dropdown that shows the type and then shows the correct fields once selected?

[Serializable]
public class Potion : Item {
  public Color color;
}
leaden ice
warm rose
warm rose
#

Anyone know what to do?

halcyon nimbus
wild vigil
#

I am adding elements of one list to a new list, and I want to make sure that as I add them that they do not already exist in my new list.

leaden ice
#

Do you need the order to be preserved?

wild vigil
#

order is not important

hasty canopy
#

Can't we just use
if(!list.contains(object)) list.add(object);
Here?

leaden ice
#

sure but that's really fucking slow

hasty canopy
#

No I'm asking praetor lmao

leaden ice
#

HashSet is the right way to do it

hasty canopy
wild vigil
#

The list will only ever be a handful of objects

leaden ice
#

doesn't matter much then, but HashSet is still semantically cleaner

warm rose
#

Why can't I jump in unity

leaden ice
#

you just do:

myHashSet.UnionWith(myList);``` and you're done
hasty canopy
leaden ice
#

or myHashSet.Add(newObject);

#

no checking required

warm rose
#

I also followed tutorial cuz my script didn't work

#

And the tutorial didn't work

#

Could It be a problem with my system itself

rain minnow
# hasty canopy Ahh alright

HashSet contains no duplicates, therefore, eliminating the need to check for an element before adding . . .

mental rover
warm rose
#

So how should I fix it?

#

Should I send my code

rain minnow
hasty canopy
rain minnow
warm rose
#

Its the same code

#

Here's the code

#

I tried logging it

#

But i dont even think its detecting my space key

hasty canopy
warm rose
#

Nothing shows up in debug

hasty canopy
warm rose
#

I logged that

#

And it showed up in the debug

#

Everytime I hit the ground

hasty canopy
#

Also can just make isGrounded bool serialized so we don't have to debug that, and can just look at it in inspector

warm rose
#

Jump doesn't

#

In debug

hasty canopy
#

Maybe "jump" doesn't exist in the valid inputs, did you try using KeyCode.Space?

#

It's frankly better than string comparison anyway

warm rose
wild vigil
#

How does hashset work? Thanks for the suggestion - it appears to be working. I just don't know how.

hasty canopy
warm rose
#

Oh wait

#

That might be the problem

#

IDE

#

I don't see underlines

hasty canopy
warm rose
#

I'm gonna try

rain minnow
warm rose
#

Ok sorry

dusky spear
#

Would it be possible for me to make something like freeform 2d light but have the shape be able to be edited by a script?

fervent burrow
#

Hello there, I have a problem where my boss (acting like a turret) isn't aiming down to the player properly, it points at the player direction, but with the wrong rotation

#

looks like this

dusky spear
fervent burrow
#

this is the code I have for the turret/boss

dusky spear
#

Ah cool!!!!

#

But can I update this while the game is running for dynamic lights?

#

Or does it need to happen only at the beginning

leaden ice
#

I don't see why not

dusky spear
#

Cool

earnest gazelle
#

Do you prefer to merge git feature branches with -no-ff?
what about main/develop to master or hotfix to master?

fervent burrow
#

can someone help me, I´m not figuring out how to fix the boss head rotation towards the player

fervent burrow
#

where would I put that in my code?

swift falcon
#

Is it good practice to put conditions on the calling of a function rather than inside? I'm thinking ground check for a jump function and such. It would improve performance right?

knotty sun
swift falcon
dusky spear
fervent burrow
#

3D

fervent burrow
steep scarab
#
#

NEVERMIND I GOT IT WORKING OH MY GOD

fervent burrow
#

I got it almost working, but the head is facing sideways

#

even if I rotate it, the head still faces that way

hasty canopy
fervent burrow
#

nop

hasty canopy
#

In that case i would recommend caching your player with serializeField first, and for testing pull the "lookat" line outside the if condition to see if it's working correctly

swift falcon
#

Is it possible to check the inspector of a different scene during runtime? My checkpoints objects seem to be surviving the Destroy() function that's called on SceneLoad

leaden ice
#

not sure what you mean about "checking the inspector of a different scene"

next seal
#

Can an editor window make an event call (tahts just what im calling an event happening) and a scriptable object listen to said event?

#

Because I need a way to update a node that is a scriptable object but I cant use OnGUI because that is editor based

#

and I have an editor that COULD theoretically call an event but im unsure if that interaction even works

#

All I need is for the Scriptable object to always access a certain Editor Window and check what is the currently active object in it, but idk what I should use for that, the Editor WIndows active Object obviously only gets updated once in a while so IDK what exactly to use to update that "active object" in the scriptable object

swift falcon
# leaden ice not sure what you mean about "checking the inspector of a different scene"

Class Goal handles the Scene loading and it's a regular LoadScene() to get back to the main menu
Class CheckPointManager has a singleton to keep the CheckPoints through Scene reloads
Class CheckPoint sets the transform.position

My problem is that from the main menu when I go back into the level, it loads at the last checkpoint. I assume it's because my PlayerManager's Awake() function loads the last transform.position from the CheckPoint class as it somehow survives? I'm not sure to check if the singleton is properly destroyed

leaden ice
#

is this a DDOL singleton?

#

Naturally it lives through scenes

feral gorge
#

Greetings, how do I create a 'DestroyAfterTime' script to be triggered after another specific script?

leaden ice
#

which will delay the Destruction for that time

#

not sure if that's what you're asking for

#

after another specific script
is kinda vague so not sure what you mean by it

feral gorge
#

I want it to trigger only after JointDismemberPhysics

#

Ill paste the script

leaden ice
#

what is JointDismemberPhysics?

feral gorge
#

It's a script for dismembering ragdoll joints after a strong collision

leaden ice
#

a script, or a method?

feral gorge
#

yes

#

one sec

leaden ice
#

which one lol

hasty canopy
#

Yes

simple egret
#

inclusive or

#

oh god

#

!code

tawny elkBOT
#
Posting code

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

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

feral gorge
#

apologies

#

long story short, I'm trying to combine the two scripts at the end of the day

leaden ice
#

which scripts

swift falcon
feral gorge
#

JointDismemberPhysics and DestroyAfterTime

leaden ice
leaden ice
feral gorge
#

yes

feral gorge
#

under the visual scripting channel?

leaden ice
#

Are you using usual Visual Scripting? (Bolt)

feral gorge
#

Visual Studio actually

leaden ice
#

that's...

#

no

#

not the Visual Scripting channel

#

that's for Bolt

feral gorge
#

ok Ill try again

#

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

[RequireComponent(typeof(Joint))]
public class JointDismemberPhysics : MonoBehaviour {
[Header("Parameters")]
[ReadOnlyField(true)]public float breakForce = 1000;
[ReadOnlyField(true)]public float breakTorque = 1000;
private RagdollDismembermentVisual visual;
private Joint joint;
private float sqrBreakForce;
private float sqrBreakTorque;

private void Awake()
{
    sqrBreakForce = breakForce * breakForce;
    sqrBreakTorque = breakTorque * breakTorque;
    visual = GetComponentInParent<RagdollDismembermentVisual>();
    joint = GetComponent<Joint>();
    visual.OnDismemberCompleted.AddListener((string name) =>
    {
        if (name == this.name)
        {
            joint.breakForce = 0;
            Destroy(this);
        }
    });
}
private void FixedUpdate()
{
    var sqrTimeScale = Time.timeScale * Time.timeScale;
    if (joint.currentForce.sqrMagnitude* sqrTimeScale > sqrBreakForce ||
        joint.currentTorque.sqrMagnitude * sqrTimeScale > sqrBreakTorque)
    {
        BreakJoint();
    }
}
public void BreakJoint()
{
    visual.Dismember(name);
    enabled = false;
}

}

simple egret
#

Nope, still not right

leaden ice
#

!code

tawny elkBOT
#
Posting code

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

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

feral gorge
#

ok

#

Ill Try creating a save as clone to experiment

simple egret
# tawny elk

If you don't understand what this says, say so

#

You're not making much sense right now

hexed geode
#

how do i clamp the magnitude of a vector without normalizing it?
i'm making a player movement script and i'm just doing this

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

Vector3 move = transform.right * x + transform.forward * z;```
but because of that, you go faster if you hold, say, W and D at the same time, and i don't want that, but just using move.normalized wouldn't work
jaunty needle
#

Hello guys, I have this function but it's not working as intended


    void Zoom()
    {
        Vector2 distanceFromCursor = (cam.ScreenToWorldPoint(Input.mousePosition) - cam.transform.position);

        if (Input.mouseScrollDelta.y < 0f)
        {
            cineMachine.m_Lens.OrthographicSize += 0.1f * sensitivity;
        }
        else if (Input.mouseScrollDelta.y > 0f)
        {
            cineMachine.transform.Translate(distanceFromCursor * Time.deltaTime);
            cineMachine.m_Lens.OrthographicSize -= 0.1f * sensitivity;
        }

        cineMachine.m_Lens.OrthographicSize = Mathf.Clamp(cineMachine.m_Lens.OrthographicSize, 1f, 100f);

        GameManager.orthoSize = cineMachine.m_Lens.OrthographicSize;

    }
tawny elkBOT
#
Posting code

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

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

jaunty needle
#

Yes yes, I misclicked

#

Anyways, so what I want is a zoom that tracks the position of the mouse

#

So it doesn't zoom to the center of the screen all the time, but it feels off, I will send a video (also I'm using cinemachine)

potent sleet
#

set your cam to temp look at set target where mouse is

jaunty needle
#
void FollowPlanet()
    {
        if(Input.GetMouseButtonDown(1))
        {
            Vector2 mousePos = Input.mousePosition;
            Ray mouseRay = cam.ScreenPointToRay(mousePos);
            RaycastHit2D hitInfo = Physics2D.Raycast(mouseRay.origin, mouseRay.direction);

            if(hitInfo.collider != null)
            {
                cineMachine.m_Follow = hitInfo.collider.transform;
            }
            else
            {
                cineMachine.m_Follow = null;
            }
        }



    }


Like here?

potent sleet
jaunty needle
#

yes... but how would I make it temp follow?

#

or temp look

potent sleet
#

or create an empty transform since I think follow target only uses transform ?

#

then make that follow mouse pointer whenever you're zooming

jaunty needle
#

hmm alrighty imma try that

#

wait can I just create a new gameobject reference and instantiate that?

#

I forgot how to create an empty transform...

somber nacelle
#

but to fix your issue you just normalize the vector then multiply by speed

next seal
#

can someone explain to me why the upper version is wrong even though I thoguht thats how we have to do it? just trying to learn here c:

potent sleet
next seal
#

well it says that its trying to convert a void into string or the other way around but I just dont see it

somber nacelle
next seal
#

What kind of void I havent even written a void here

next seal
#

I thoguht the top line was saying

next seal
#

"take the i value of this item, then for that number do this thing"

#

like for example I thought it would take the first object and in the first line display the field, then so on for the rest

#

but alas I have been wrong

#

thanks for teaching me guys

misty blade
#

Hello! I'm working on a 2D "decal" system for a pixel art game. Code below works almost perfectly, but every decal is moved by a half pixel. Do you know how to fix that? (The green stuff on the pixture are the decals and grid behind them is a testing object)

private void SnapToPixelGrid()
    {
        transform.localPosition = new Vector3(
            RoundToNearestGrid(transform.localPosition.x),
            RoundToNearestGrid(transform.localPosition.y),
            transform.localPosition.y);
    }
    float RoundToNearestGrid(float pos)
    {
        float xDiff = pos % pixelGridSize;
        pos -= xDiff;
        if (xDiff > (pixelGridSize / 2))
        {
            pos += pixelGridSize;
        }
        return pos;
    }
hexed geode
somber nacelle
hexed geode
# somber nacelle clamp magnitude is not the solution you are looking for. it is the answer to you...

but the Horizontal and Vertical axises smoothly go from 0 to 1 and back the when you're pressing the buttons, so normalizing the move vector would mean that you would still be moving when you release the move buttons because the axis value would still need to go from 1 to 0 unless you mean normalizing the vector even before multiplying it by Horizontal and Vertical axis which i have just realized you might've meant

#
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = (transform.right + transform.forward).normalized;
        move.x *= x;
        move.z *= z;

i suppose doing this is better?

somber nacelle
#

no

#

you're still not normalizing your input

hexed geode
#

why would i need to normalize my input

somber nacelle
#

btw you can use transform.TransformDirection to convert the direction to be relative to the rotation of the object instead of multiplying the transform.right and transform.forward

somber nacelle
hexed geode
somber nacelle
#

again, don't even bother using those, use the TransformDirection method instead

#

but if you don't normalize your input then it will also be (1,0,1) when moving diagonally

maiden fractal
maiden fractal
#

Just clamp the magnitude of the input vector to 1

hexed geode
maiden fractal
#

Vector3(Horizontal, 0, Vertical)

hexed geode
#

but you just said it'll ignore the acceleration of input axes

maiden fractal
hexed geode
#

Oh I see ye

#

But I think normalizing the (transform.right, 0, transform.forward) vector is better though

#

or using TransformDirection like boxfriend said

maiden fractal
long fox
#

Does anyone actually know hood tuturials for vr coding

hexed geode
leaden ice
#

I don't think they do a lot of VR coding in the hood

somber nacelle
hexed geode
#

ok fair

jaunty needle
#

I still think the translate method could work

potent sleet
#

I think it should be the lookat target

jaunty needle
#

hmm ok

cinder ether
#

Hello, rider can't find the Resources class from UnityEngine, even with a using UnityEngine; in my files
I explicitly need to type UnityEngine.Resources to make it work, but what's disturbing is that happened suddenly, before, everything was fine...
Any idea ?

#

The error: The type or namespace name 'Load' does not exist in the namespace 'Resources' (are you missing an assembly reference?)

proper oyster
simple egret
#

See it interprets Resources as a namespace instead of a class, something's wrong here

#

The compiler picked up the wrong one, do you have your own Resources namespace?

cinder ether
#

Mmh no, I don't think so

#

Oh maybe

#

Yep that was that

simple egret
#

You'll need to fully qualify the name UnityEngine.Resources.Load<T>("...") if you wish to keep your own Resources namespace

potent sleet
cinder ether
#

No that's ok. What happened I think is, because my script files are stored in a Resources folder, rider created the Resources namespace for me when I created a file

#

I usually create files from explorer or unity, that's why it didn't happen before..

simple egret
#

Ah yeah that's why, Unity applies their own script template which dumps everything into the global namespace

cinder ether
#

Yup

lucid valley
jaunty needle
cinder ether
#

I may not need them to be in Resources, but since i put every asset in Resources, I said maybe why not storing scripts here too

#

I guess that's wrong

potent sleet
lucid valley
cinder ether
#

Okay, gonna clean up all this once

jaunty needle
cinder ether
#

Otherwise, you guys know how I can remove this error from spamming my Console ?
[Collab] Collab service is deprecated and has been replaced with PlasticSCM
I uninstalled the Version Control package, but it keeps spamming this error every second

#

that's not blocking me from building the project or whatever, but it's annoying

jaunty needle
#

However, this skips a lot cause of the mouseDelta

#

Is there a workaround for this?

#
        {
            Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
            cineMachine.transform.Translate(distanceFromCursor * Time.deltaTime * zoomSpeed);
            
            cineMachine.m_Lens.OrthographicSize -= 0.1f * sensitivity;
        }

The piece of code btw

#

zoomSpeed is the variable I can change and the larger it is, the faster it zooms in butt it skips a lot

#

Acc nvm it's not that big of an issue

fossil moat
#

hello, i want to make a map in the style of avorion, ie : a big square map divided in a lot of square, i want to be able to visualise the whole map at once, being 50x50 or even 100x100 or maybe more. each tile would have to contain data about what is in this tile and be able to show it when i click with my mouse on it.

The main issue i have is that i don't really know how would i approach that, there's the tile system but i'm not sure it fits that purpose really well.
The other option i had was making every tile be a gameobject and have a script to generate the map randomly assigning stuff to each tile. that option would lead to having a lot of displayed gameobject which isn't optimal.
Another way i'm thinking about would be to have few gameobjects but the data is accessed by looking at where the mouse is on that gameobject which could allow to have only 1 gameobject for a square map and i would just have to find a way to put highlights on the tile i am looking at.

My question being, i feel very confused and don't know which of these options is suitable or would work, which do you think is better or is there another way i didn't see?
Also here's kinda what it will look like on a very bad sketch

swift falcon
#

I'm completely lost trying to manually destroy a DDOL class from another class when a new scene loads.

Currently I have Class cpm
Destroy(cpm.gameObject)

However it just does not work

mental rover
swift falcon
mental rover
# fossil moat hello, i want to make a map in the style of avorion, ie : a big square map divid...

I'd try to hold on to the idea of separating the logic of your game from the representation of it - your data for each tile and what each tile does can be entirely written with simple C# classes. You could then start with the idea of having a GameObject for each tile just as a point of interaction to access the tile data class underneath such as handling OnClick events, etc, and if performance becomes a concern the data layer will be intact and you can just change how it's represented

mental rover
swift falcon
#

My CheckPoint script is where I set the transform.position

mental rover
#

your PlayerManager isn't interacting with CheckPointManager here?

swift falcon
#

No

mental rover
#

so why would destroying CheckPointManager do anything?

swift falcon
#

My checkpoints object are children of my CheckPointManager

mental rover
#

the lastCheckPointPos is what you need to look at resetting when the scene starts/returns to main menu

#

this doesn't look like it has anything to do with the object you're trying to destroy

swift falcon
#

Ok ok

#

Actually makes sense now that you say it, thank you!

fossil moat
jaunty needle
#

How do I have this accelerate over time?

#

Right now it's constant and it doesn't feel as good

mental rover
knotty sun
jaunty needle
#

...yes

hexed pecan
knotty sun
#

increase the value of orbitZoomSpeed * Time.deltaTime over time then it will accellerate

jaunty needle
# hexed pecan Are you updating currentOrthoSize though?

Yes

    {
        while(true)
        {
            float currentOrthoSize = cineMachine.m_Lens.OrthographicSize;
            cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
            if(cineMachine.m_Lens.OrthographicSize == expectedOrtho)
            {
                break;
            }
            yield return null;
        }

    }
#

Ok yeah I think I can do it

simple edge
hexed pecan
#

Looks like it should work, unless the == fails because of floating point imprecision

jaunty needle
jaunty needle
hexed pecan
jaunty needle
knotty sun
jaunty needle
#

I mean, it broke when I removed it soo

#

Unless you have an alternative

knotty sun
#

set it once not every time in the loop, you are almost implementing a lerp

jaunty needle
potent sleet
#

keyword almost

jaunty needle
#
            cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
            orbitZoomSpeed += 1f;
            orbitZoomSpeed = Mathf.Clamp(orbitZoomSpeed, orbitZoomSpeed, maxOrbitZoomSpeed);

Unfortunately this did not work either

knotty sun
jaunty needle
#

Wdym by wrong

knotty sun
#

yes

#

it is a virtually constant value, it shouldn't be

jaunty needle
#

soo, what should it be then?

knotty sun
#

I did ask if you understood basic maths

jaunty needle
#

I do, however I do not understand it as well when it comes to C# and Unity, I'm barely surviving here

knotty sun
#

you need a value that goes from 0 towards 1 incrementing every loop, to accelerate you need an additional multiplier to make that acceleration

jaunty needle
knotty sun
jaunty needle
#

I...ok

#

How am I supposed to know he's an idiot?

knotty sun
#

basic maths

jaunty needle
#
        float maxDelta = 0f;

        while (true)
        {
            cineMachine.m_Lens.OrthographicSize = Mathf.MoveTowards(currentOrthoSize, expectedOrtho, maxDelta);
            maxDelta += 0.1f;
            maxDelta = Mathf.Clamp01(maxDelta);

            if (cineMachine.m_Lens.OrthographicSize == expectedOrtho)
            {
                break;
            }
            yield return null;
        }

    }

Idk man but this don't work

knotty sun
#

i give up

jaunty needle
#

Lemme just tell you, you are not a very patient person

potent sleet
simple edge
jaunty needle
#

Now I'm extra confused

simple edge
#

For testing purposes you could try throwing in a really high value orbitZoomSpeed, and that should get clamped to the expectedOrtho

hexed pecan
#

Idk what the others are saying. This is not Lerp, it is MoveTowards

potent sleet
#

I just threw a link, suggested they use lerp instead

hexed pecan
#

Yeah but Steve was talking about 0..1 range which is a lerp thing

hexed pecan
potent sleet
#

yes Idk if I'd call Taro an idiot xD

simple edge
#
public class test : MonoBehaviour
{
    void Start() => StartCoroutine(SmoothOrbit(200, 10));

    IEnumerator SmoothOrbit(float expectedOrtho, float orbitZoomSpeed)
    {
        while (true)
        {
            Camera.main.orthographicSize = Mathf.MoveTowards(Camera.main.orthographicSize, expectedOrtho, orbitZoomSpeed * Time.deltaTime);
            if (Camera.main.orthographicSize >= expectedOrtho)
                break;
            yield return null;
        }
    }
}

Just threw this together and it just works 🤷‍♂️

hexed pecan
#

What if it starts at a larger value already

simple edge
#

oh sure true

#

it was just for demonstration purposes, to show that there is nothing wrong with the logic

hexed pecan
#

So seems like Steve is the only one confused here lol

simple edge
#

like, you can throw that script anywhere in your scene, and you should just see an orthographic camera's size increase

jaunty needle
jaunty needle
jaunty needle
#

In conclusion, don't insult my boy Taro

left narwhal
#

I'm making a game with an infinite procedural world with randomly generated structures, objects, etc. The idea is that I add pathfinding so that NPCs and animals can move around and go inside of houses and such. The problem however is that the current method I'm using is too slow and unreliable. My current approach is to separate the world into chunks of 8x8 blocks that I'm using the A* algorithm on to generate a general path. Then I use A* again but this time I run it on the blocks that are inside of these chunks to generate a path.

#

My question is, what would be a better approach to this, or how would I be able to optimize (maybe using threading or something? No clue)...

vocal merlin
next seal
#

Main Code
https://pastebin.com/YLDBCPuM
https://pastebin.com/Fm5kp8Lk

(Inherits from these)
https://pastebin.com/dZQukmaF
https://pastebin.com/H9TSpQv2
https://pastebin.com/Zw79eyuH
Can someone help me? I am absolutely losing my mind ive been at this for like hours.
All I want to do is get the Editor window automatically display parent
Dialogue Objects connected to its node on the left and child/answer Dialogue Objects to automatically display on the right with the connections

Everything that is required is theoretically there I just cant figure out this last bit where I have to feed the start and end pos into DrawNodeCurve T_T

Please feel free to DM me as this might not get solved immediately

#

I tried literally everything in the DialogueNode script thats why there are so many DEW things at the top

#

and its kind of a mess right now because I tried so many things ;(

#

This should theoretically get the start and end position and then draw the like connection between the nodes (each dialogue object being a node)

#

If someone finds this later and wants to help me just msg me DM

left narwhal
#

as the wiki doesnt show how to use it besides setting it up

#

is it just a normal navmesh?

vocal merlin
#

Did you look at that page?

left narwhal
#

yes i did

vocal merlin
#

I haven't used it myself yet, but I am planning to

next seal
#

If someone finds this later and wants to

loud wing
#

Hello guys, hope all is well. Can someone please help me connect my login scene to my register scene

heavy nexus
#

Hey uh - whats one of those sites where you can put ur code in for others to see

loud wing
#

github?

#

oh nvm ik what you're talkin about

#

i forgot

heavy nexus
#

its basically google docs with code formatting come to think of it

#

yea

loud wing
#

pastebin?

heavy nexus
#

thats the one

loud wing
#

kloak you know how i can connect my scenes in unity?

#

im new kind of need help

heavy nexus
#

Ive struggled with that in the past myself, Ive never figured it out aha

#

Alrighty - Hey so I made this kinda.. flying lump thing

#

I just wanted to to flying with acceleration and deceleration

swift falcon
#

pls somone help im trying to make car like beamng drive becasue i cant afford it
i made a car it has wheels window but they all fell apart
how connect all parts together

heavy nexus
#

and Im aware this is probably done really stupidly

heavy nexus
left narwhal
#

lmao

swift falcon
heavy nexus
#

hm

swift falcon
#

is that ok

heavy nexus
#

weird

#

that sounds correct so far

left narwhal
#
        List<Vector4> openNodes=new List<Vector4>{new Vector4(startCell.x,startCell.y,0,-1)};
        List<Vector4> closedNodes=new List<Vector4>();
        int iteration=0;
        List<Vector2> exploredCells=new List<Vector2>();
        Vector2 resultCell=new Vector2(Mathf.Floor(endPosition.x*RegionHandler.chunkSize),Mathf.Floor(endPosition.y*RegionHandler.chunkSize));
        Vector4 pathResult=new Vector4(0,0,0,-1);
        while(openNodes.Count>0&&iteration++<2048) {
            if(resultCell==new Vector2(openNodes[0].x,openNodes[0].y)) {
                pathResult=openNodes[0];
                break;
            }
            if(!exploredCells.Contains(new Vector2(openNodes[0].x,openNodes[0].y))) {
                exploredCells.Add(new Vector2(openNodes[0].x,openNodes[0].y));
                for(int i=0;i<4;i++) {
                    Vector2 moveDirection=new Vector2((i+1)%2*(i>1?1:-1),i%2*(i>1?1:-1));
                    Vector2 newPosition=new Vector2(openNodes[0].x+moveDirection.x,openNodes[0].y+moveDirection.y);
                    if(!walkableCells.Contains(newPosition)) continue;
                    float gCost=Mathf.Abs(openNodes[0].x-startCell.x)+Mathf.Abs(openNodes[0].y-startCell.y);
                    float hCost=Mathf.Abs(openNodes[0].x-resultCell.x)+Mathf.Abs(openNodes[0].y-resultCell.y);
                    float fCost=gCost*.25f+hCost;
                    openNodes.Add(new Vector4(newPosition.x,newPosition.y,fCost,exploredCells.Count-1));
                }
                closedNodes.Add(openNodes[0]);
            }
            openNodes.RemoveAt(0);
            openNodes.Sort((a,b)=>a.z.CompareTo(b.z));
        }
        if(pathResult.w==-1) return null;```
swift falcon
#

i put rigid body on them is that ok

left narwhal
heavy nexus
#

Anyway I have this flying lump, I tried to do it with acceleration, and its probably really really overly complex,
It sometimes has this weird bug where the movement will be really.. not smooth

here is my code https://pastebin.pl/view/14911c6b

heres the video https://www.youtube.com/watch?v=Vx9vLH2I1PE&ab_channel=Kloakk

#

you can see inconsistencies in the movement

#

around 13 - 15 secs in its rly obvious

left narwhal
#

i recommend you rewrite your code

left narwhal
swift falcon
#

help

heavy nexus
#

yyyyyeah I probably should

#

I just wanted to throw smth together in like 10 mins

left narwhal
#

also use a min max for your velocity i guess...?

heavy nexus
#

n Im not too great with vector3s yet

#

oh I do

left narwhal
#

and use += instead of currentVelocity=currentVelocity+acceleration*Time.deltaTime;

heavy nexus
#

ah ok

left narwhal
#

also i think its because youre

#

handling deceleration

#

based only on axes...

heavy nexus
#

hmmmmmmmmmmmmmmmmm

left narwhal
#

i would handle it with rotation too

heavy nexus
#

wdym

left narwhal
#

basically something like

#

also deceleration from friction

#

is usually handled in factors

#

not with addition

tardy trail
#

can someone edit a script for me to set rotation for the object to the controller rotation (already included as gameobject bool) If yes dm me

left narwhal
#

so i would just say velocity*=0.98

#

instead of using a deceleration constant

heavy nexus
#

Ill give it a go

#

see if it does anything

left narwhal
#

basically

heavy nexus
#

basically... use vectors?

left narwhal
#
Vector3 shipVelocity=new Vector3(0,0,0);
float acceleration=0.03f;
float decelerationFactor=0.98f;```
#
//accelerating
shipVelocity+=new Vector3(movement.x,movement.y,movement.z)*acceleration;```
heavy nexus
#

blimey I have a lot to learn

left narwhal
#

where movement is a new Vector3

#

that you create

#

and set the x y and z to depending on the keys you use

#

0 is standing still

#

-1 is backwards

#

1 is forwards

#

repeat for all axes

heavy nexus
#

ah thats why I was confused

tardy trail
#

can someone edit a script for me to set rotation for the object to the controller rotation (already included as gameobject bool) If yes dm me

left narwhal
#

then just position+=shipVelocity

heavy nexus
#

this might be a really dumb question right

left narwhal
#

yes

heavy nexus
#

actually no it is

left narwhal
#

right

heavy nexus
#

Ill give it a go

#

see how it does

left narwhal
#

so you can rotate your ship

heavy nexus
#

ah yeah, that was gonna be the next bridge to cross

left narwhal
#

mhm

left narwhal
heavy nexus
#

when you said do a vector3 for each axis I thought do 3 vectors3s

left narwhal
#

haha why

heavy nexus
#

and then realised that would be stupid

#

honestly not a clue

left narwhal
#

Vector3 is already three axes

heavy nexus
#

indeed it is

#

unity is soup I am fork

left narwhal
#

its all right

#

how longve you been coding

fringe valve
#

Hey all, forgive me if this is the wrong spot to ask -

Created a 3D game, but need access to a Hexagonal Tilemap asset. The 2D GameObject menu is missing from my GameObject menu, of course.

https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html

Having read online that you should be able to bring these into a project via a package import,

Anyone know where can I find the standard Unity 2D assets package so that I may do this?\

left narwhal
#

google

#

i guess

#

its literally

#

2d object>tilemap>hexagonal tilemap pointed top

#

in your context menu

#

are you using the last version of unity

fringe valve
#

I've spent a bit googling around for where I can find/download the 2D standard assets to no avail, I'm new, so I'm probably not referring to it correctly.

I've already said in the original question that it's not there, since this project was created as 3D.

heavy nexus
#

wbu

heavy nexus
fringe valve
# left narwhal create a 2d project...

This is not a project that was created by me, and it already has significant work done on it guys. I asked a specific question here about how to find the unity standard 2D assets so that I can import them into any project. If you guys don't know this, you don't have to respond

left narwhal
#

then explain that in your question

#

no need to get passive aggressive

#

theres a reason you cant use standard 2d assets in 3d projects btw

fringe valve
# left narwhal then explain that in your question

Having read online that you should be able to bring these into a project via a package import,

Anyone know where can I find the standard Unity 2D assets package so that I may do this?\

Note the original wording

mental rover
fringe valve
left narwhal
mental rover
#

what are you trying to do that isn't currently possible/available in the project?

fringe valve
mental rover
#

you will need to download the 2D Tilemap Editor package via the Package Manager.

fringe valve
#

I'll see if I can't figure out why I can't see standard assets in my import dropdown then, signs point to that being a potential problem/fix

#

Unsure if any of this is is due to the fact this project is checked out from source control and some dotfile somewhere is being .gitignore'd, but my package manager has nothing in it.

Possible red herring, but I also don't see any scoped registries here in Project Settings, is this supposed to be populated?

#

I promise y'all I'm not trying to waste your time or be obtuse here

mental rover
#

click the dropdown "Packages: In Project"

#

search the Unity registry for it

fringe valve
#

NICE! Yeah that's it

#

Beautiful, thanks so much

left narwhal
#

also i feel like this shouldve been in a different channel maybe

wanton obsidian
#

So, Anyone know why a characterController would return isGrounded false when I'm not moving but does return true if im moving and on the ground but even then sometimes it goes back and forth?