#archived-code-general

1 messages ยท Page 64 of 1

swift falcon
#

Unity Character controller

glossy basin
swift falcon
#

Forgive me if were u already asked this but make sure u have the visual studio code plugin installed in ur package manager

#

and make sure its up to date

swift falcon
#

And yes storm

glossy basin
#

Alright, so you need to download this package "Visual studio code editor"

#

its on the package manager

swift falcon
#

They all have box collider2D because its a 2D game

#

None of them are set to trigger

glossy basin
#

I faced the same issue but with my own controller

swift falcon
#

I cant add a rigidbody

#

It says It conflicts with the character controller

glossy basin
#

I dont really like / use built in character controller

swift falcon
#

Is this it?

glossy basin
swift falcon
#

Yea its already installed tho...

#

Ok, so it's there and up to date.

#

theres a .json file u need to check

glossy basin
swift falcon
#

aaahhh i see

#

Is there something I need to do on VS's side?

#

U can try installing the unity whatever its called

#

U have to do that in vs code tho

swift falcon
strong forge
#

I've solved it. Since I am calling this function from a websocket running on a Node server, it wasn't running on Unity's main thread, so I had to sync it.

swift falcon
#

The thing that's for Visual Studio and not Visual Studio Code?

glossy basin
# swift falcon Is there something I need to do on VS's side?

It seems you need to setup some things on VS code, this video might help https://www.youtube.com/watch?v=1saf4ahn-ek

Visual Studio Code is a source-code editor made by Microsoft for Windows, Linux and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git. Users can change the theme, keyboard shortcuts, preferences, and install extensions that add additional functionality.

...

โ–ถ Play video
swift falcon
#

No again Visual Studio and Visual Studio Code are not the same thing

#

Precisely.

#

Theres something on visual studio Code Where u can install extensions

#

Ok.

#

Install the one thats for unity

#

DO NOT DOWNLOAD THE DEPRACTED ONE

glossy basin
swift falcon
#

itll be grayed out

#

@glossy basin i told him the same thing lol i was the one that told him to come here lmao

glossy basin
#

@swift falcon may I ask why are you using vs code instead of standard one?

glossy basin
#

did you solve the collision problem?

swift falcon
#

Im trying it rn

#

And yeah i would say just use Normal Visual Studio its 10x better in my opinion

swift falcon
#

No it didnt work sorry

glossy basin
swift falcon
#

I wanted to use a rigidbody on my player but it causes this weird blur effect

#

Ive always had this problem in unity

glossy basin
#

its not good for large projects or complex ones which require physics manipulation

swift falcon
#

Anytime i set the camera to follow a rigidbody it does this... I know they work on different intervals FixedUpdate(rigidbody) and Update(camera) hence the camera glitching

glossy basin
#

I would suggest you implement your own, as it is extremely easy

swift falcon
#

I know how to but that still requires a rigidbody for collision

#

I mean i guess i could actually just do what u said earlier which was a put rigidboy on everything else

#

Lemme try that without the character controller

glossy basin
#

it should work that way

#

if not, then something must be messed up on your project settings

swift falcon
#

It does

#

I dont why i didnt just listen lmao u literally gave me the answer. I was just frustrated i guess sorry and thank u

swift falcon
#

In my installation.

glossy basin
swift falcon
#

k

glossy basin
#

If that setup did not work, then I suggest switching to standard VS, it is ready to use with unity

swift falcon
#

OOOHHHHH I see what this means now!

glossy basin
grave canyon
#

anyone able to help me to add paypal payment into my site ?

grave canyon
glossy basin
grave canyon
wheat plume
#

mb

#

it was just a massive text file that had like 1 billion characters in I think it was arabic

quartz folio
#

@wheat plume do not post random exes

wheat plume
#

k

#

it was a text file but renamed to .exe

thin perch
#

Hi all, does anyone know what Chrome OS evaluates to in Application.platform ?

#

i don't see it listed in the public enum RuntimePlatform

thin perch
#

i would assume linux, but seeing that a bunch of android native feature work, i have no clue without a chromebook to test on lol

gray zephyr
#

For monobehaviours that react when a button is pushed, how do I move from polling the button every frame to pushing a buttondown event? does Unity have anything built-in for that?

#

like I want to get rid of void Update() {if (Input.GetMouseButtonDown()){...}}

latent latch
vagrant blade
#

The new input system is event based, yes. So it happens when the button is pushed, and you don't have to check it in Update as with the old system.

swift falcon
#

how do i get an input fields text as a variable string

swift falcon
# glossy basin Makes sense

So now, after a lot of other downloads (thanks to Visual Studio telling me of different packages to download one at a time and me unticking the option that used only the newest .NET SDK), it finally works. ๐Ÿ˜„

#

Thanks!

#

i did public InputField[] usernamee;

glossy basin
swift falcon
glossy basin
swift falcon
#

yeah

#

exactly

#

ike i have an input field and uh i want it to be their username they type in their username and in the script it sets the string variable to waht they typed

glossy basin
junior aurora
#

anyone know resources i can look for to make a 2d world where it can be very large and have things like trees, or villages on them?

swift falcon
#

it says input field does not have a definition for value

#

@glossy basin

#

X_X

glossy basin
#

are you defining your input field as InputField[] MynputField; or as InputField MynputField;

#

@swift falcon

swift falcon
#

uh

#

idk which one do i use

glossy basin
swift falcon
#

idk ive tried multiple

glossy basin
#

that should worl

#

work

swift falcon
#

it says it has no definition for text either

#

wait no that worked i think

#

i hate unity

full scaffold
#

Are you using TextMeshPro?

#

You need to use TMP_InputField (or something similar of the sort) if you are

swift falcon
#

i got it thanks guys

#

โค๏ธ

#

gex 64 leaderboards

gray zephyr
#

hey dawgs

which gang are you in

// For single-statement ifs

if (conditional) format = "One Line";
// or
if (conditional)
    format = "Indented Newline";
simple edge
#

I do whatever stylecop/codemaid/jetbrains wants me to do
So that's the latter

I find it's best to leave that work to some arbitrary algorithm than waste my own time on it and still mess it up every so often

#

It also helps when collaborating, because you enforce one style

hard estuary
paper heart
#

help please?

merry sequoia
#

Show me the code you use to trigger the animation

#

I think itโ€™s because of how your inputs are handled but Iโ€™m not sure

thin aurora
gray zephyr
#

Sure hope the compiler optimizes that the same as the others

thin aurora
gray zephyr
#

I'm not sure where I heard it but I thought no brackets = faster somehow

thin aurora
#

Your code is lowered into a version with brackets. So no, not really

#

In my opinion leaving out brackets is prone to cause errors, should your one-liner turn into a two-liner, or you end up formatting it in a way that invalidates your if-statement. Since if-statement do not require an explicit body if done wrongly, it can be a cause of quite the bug...

#

IMO it's also just more readable.

deep fable
rugged plume
#

hey i wanted to ask, with wheel colliders, what is motortorque

#

as in what does it represent

#

is it speed of the wheel, or the acceleration of the wheel

#

and assuming i kept the valuje of motortorque the same, would it move at the same speed assuming consistent variables like a flat surface

tardy agate
tardy agate
#

Hi, so I have this function to move a target object with a click and drag input. Works great, however I wan't my object to collide with other object so it can never be inside another object. I used a SphereCast that detects such collision, unfortunately the formula inside that cast doesn't seem to affect my object in any way. Am I doing something wrong? Any ideas?

void TargetMovement()
   {
       if (Input.GetMouseButtonDown(1))
       {
           isTargetMoving = true;
       }
       if (Input.GetMouseButtonUp(1))
       {
           isTargetMoving = false;
       }

       if (isTargetMoving)
       {
           Plane plane = new Plane(Vector3.up, Vector3.zero);
           Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

           if (plane.Raycast(ray, out float distance))
           {
               if (Input.GetMouseButtonDown(1))
               {
                   dragOrigin = ray.GetPoint(distance);
               }
               else
               {
                   Vector3 newPosition = focus.position + (dragOrigin - ray.GetPoint(distance));

                   Vector3 direction = newPosition - focus.position;
                   float distanceToNewPosition = direction.magnitude;
                   float radius = 0.5f;
                   RaycastHit hitInfo;
                   if (Physics.SphereCast(focus.position, radius, direction, out hitInfo, distanceToNewPosition))
                   {
                       newPosition = hitInfo.point - (direction * radius);
                   }

                   focus.position = newPosition;
               }
           }
       }

       focusPoint = focus.position;
   }
quartz folio
rugged plume
tardy agate
tardy agate
rugged plume
tardy agate
rugged plume
#

yeh thatd probably work

tardy agate
rugged plume
#

ohh i know the issue

#

its my wheel collider setup

tardy agate
#

welp

tardy agate
rugged plume
#

like in gear one, only up to 60 speedvalues

#

and in gear two, only up to like, idk 120 or somethingh

tardy agate
#

really not familiar with wheel colliders but i suppose a mix of changing the torque for each gear and velocity clamp should do the trick.

#

there's probably a tutorial for that somewhere

rugged plume
#

ill give it a look, there should be 4 sure

rotund burrow
#

i'm looking for advice or good tutorials on 3d pathfinding. i want to implement jumping and flying units, for example, in a space with many floors. right now i have some code from sebastian lague tutorial and a movement system

plucky inlet
rotund burrow
trim schooner
#

A*

plucky inlet
#

ah yea, there is A*, you can try that out

rotund burrow
#

i already have basic a* as i said, i need to know how to best implement it for 3d spaces with verticality and floors

#

i mean control over ai unit. i have a movement system script which i want to use for ai units (as well as player), but navmesh uses its own thing as far as i can tell

trim schooner
#

Are you using the A* asset from the store? That has docs on how to do it

#

Where did you mention A*? ๐Ÿค”

rotund burrow
#

you mean aron pathfinding? i've looked into it but for the 3d aspect you have to pay, and i 'm not sure it's what i need

plucky inlet
#

You can always ask a refund if it does not work out for you

rotund burrow
#

i mentioned sebastian lague tutorial on the a*

plucky inlet
#

You did mention his name, not A* , just for the record ๐Ÿ˜„

mystic ferry
#

how does energy transfer work on box2D rigidbody collisions? obviously mass plays a role but does the engine also simulate other energy transfer types like heat and sound? Just not sure what actually happens

#

I know about the impulses on overlap and detecting collisions, but not the energy transfer

mystic ferry
#

well adjacently, yeah

plucky inlet
#

rigidbody is always mass /velocity related. There is nothing like heat or sound "energy" in unity because heat wont move things just by being hot

mystic ferry
#

um. Lol

#

not what I mean. When a collision happens energy is transferred between the two bodies, some energy is lost as heat and sound, friction, etc. just wondering what the depth is here

plucky inlet
#

ahhh, my bad. I thought heat as the source of energy, not the result of a collision

#

Well there is no heat or sound generation on collision. but you can always use the velocity of colliding objects and some physics knowledge to actually create your own system with resulting values

mystic ferry
#

Iโ€™m just trying to understand the base collision system essentially. When two bodies collide is it just based on mass and angle? I just want to be able to predict what a dynamic collision is going to look like

#

I want to know when I need to use kinematic rigidbodies and when I donโ€™t

simple egret
azure heath
#

Currently trying to use a Physics2D.Boxcast to return an array of touched items, as seen here: https://docs.unity3d.com/ScriptReference/Physics2D.BoxCast.html My code is as follows:

RaycastHit2D[] bashables = new RaycastHit2D[20];
            ContactFilter2D filter2D = new ContactFilter2D().NoFilter();
            if (Physics2D.BoxCast(halfHeight, box2D.size, 0.0f, raycastDirection, filter2D, out bashables, rayLength));

I can't seem to get the parameters to line up right for the version of the function I'm looking for. Can anybody here provide an example of the correct parameters?

mystic ferry
simple egret
#

Yep

#

That's not a reason to post in the wrong channel though, even if the person you're talking with knows how the physics engine works

#

Channels are driven by the subject of the question, not the knowledge of the people

mystic ferry
#

๐Ÿ˜’

wary wagon
#

Today i discovered that Unity doesnt handle references in serialization and just do everything by value ? How do you serialize graphs of stuffs ?

Should i replace every reference by identifiers and do the linking myself ?

#

( i am having a graph with backward and forward links and it is triggering depth limits errors in the serialization )

leaden ice
wary wagon
#

Isnt that costy ? I will have LOTS of small nodes

leaden ice
#

Through custom editor scripting you can shove any number of SOs you want into a single asset

#

Costly? Not really

wary wagon
#

still, that graph will be only editable while in game

leaden ice
#

If it's editable in game only then Unity serialization isn't much help. Unless you're using JSONUtility?

wary wagon
#

I plan to do that at some point yus

#

oh well maybe that json utility can actually help with references ?

leaden ice
#

Newtonsoft JSON has some support for the kind of referential serialization you want

wary wagon
#

โค๏ธ

leaden ice
#

TBH though I often end up serializing identifiers and rebuilding my graphs manually at runtime

wary wagon
#

I think im gonna do it that way too, that way i could use unity serialization and edit the stuff with the editor

#

(while runing a scene )

cobalt flint
#

When dealing with events:
When I subscribe to an event it is acceptable to be void, but when I unsubscribe it expects a return type of EventHandler, but doing so changes makes either the subscribe or unsubscribe not have a correct path, or a correct return type. What should an eventHandler return?

neat citrus
#

Hi, I use this code to rotate the rigidbody, and it rotates the x y and z axis, but i only want it to rotate x
Quaternion carXRot = Quaternion.Euler(new Vector3(0f, carRB.rotation.y, carRB.rotation.z));
carRB.MoveRotation(Quaternion.Slerp(carRB.rotation, carXRot, 10 * Time.deltaTime));

elfin tree
#

Is it normal that code like this also modifies the prefab itself?
What would be a clean way to avoid this?

trim schooner
wary wagon
#

So im doing something like this now to hold my map graph

#

I have two types, one that handles the serialization with IDs and whatenot

cobalt flint
leaden ice
cobalt flint
#

Was trying to call it like a function

#

Okay!

#

Will look into that. Ty.

wary wagon
#

Why is unity spaming serialization on my game object that is opened in the editor ? ๐Ÿ˜ฎ

#

I do nothing and i see my serialization callback called in loops

grave geode
#

Hey I need some help converting some scripts from an oculus framework to openXR / steamVR anyone know how to do it?

plucky inlet
west sparrow
grave geode
#

also I made this script like a day ago deleted it by accident now rewriting it it doesn't work?

plucky inlet
grave geode
west sparrow
#

But most likely those functions you are calling don't exist in the class. Maybe you have two 'Hand' scripts? Or you've updated a package?

#

With XR, you almost always want to use your own namespaces, as you are very likely to conflict with their package names at some point.

plucky inlet
plucky inlet
#

But anyway, if you want to convert your script to OpenXR, you have to figure out what they are doing in steamvr and then just google for that specific behaviour in the docs of OpenXR or any example project.

plucky inlet
# grave geode

whatever that should tell me besides that you include the library folder and temp in your git repo which is not a good idea

grave geode
plucky inlet
grave geode
#

so found out that the VR FPS System asset I bought had a hand script so I deleted it it almost working but IsGrabStarting isn't

west sparrow
#

I highly doubt that is a method

plucky inlet
west sparrow
#

But if it is, it would likely return a bool

grave geode
plucky inlet
west sparrow
#

Right click on Hand, go to definition, and see what alternatives are in the script.

#

But yeah I'd probably just flick through what is in autocomplete

grave geode
#

Nothing there about IsGrabStarting or any of the sort

plucky inlet
#

can you show the script of the IsGrabEnding source?

#

And where is that coming from, openXR or steamVR?

plucky inlet
#

Okay, just to clarify. You want to get rid of steamvr right to convert over to openxr?

grave geode
#

Found there is a hand.GetGrabStarting

plucky inlet
#

well that should have been quite obvious in the list ๐Ÿ˜‰ yeah I guess you just have to go manually through the scripts of steamvr and see what fits your needs

grave geode
#

Yeah seams so

plucky inlet
grave geode
#

thanks you for the help hopefully I can work my way around to get it all to work with steamVR kek

elfin tree
#

So this code is called from .GetComponent after being Instantiated. It is on a prefab and the quads are all gameobject within that prefab. Why does the prefab get permanently modified when calling the code below, shouldn't it all be instances at that point?

plucky inlet
elfin vortex
#

hey guys, I'm working on a project for college using Unity 2D and a friend wants to add a mount to the game. Anyone knows how to do something similar to Yoshi from Super Mario World?

plucky inlet
elfin tree
#

They all started as 1x1

#

But that's the prefab now

#

and other quads also permanently moved cause of other code below

plucky inlet
elfin tree
#

I don't think so, but maybe the prefab was open when the code was running?

plucky inlet
elfin tree
#

It does not, but I know in another unity version there was a warning which I could ignore when a prefab was open and pressing play

#

I'll keep testing and see if it stops happening knowing that

plucky inlet
#

yeah, maybe try to figure out the exact situation where it affects the prefab

lunar forum
#

Anyone have tips/suggestions/links on implementing a master script/scene that tracks game variables throughout the lifetime of the game? Trying to search for it doesn't yield much - probably because I just don't know what search terms I should be using.

plucky inlet
lunar forum
elfin tree
#

On another note by the way, does anyone know why first line doesn't work, but the 2nd block does work?

#

rotationToApply is not null and the changes in variables are mostly just from tests

#

also note that this code block happens after everything

leaden ice
# elfin tree

Why are you using quaternion components as if they were euler angles?

elfin tree
#

Probably because I don't know what I'm doing haha

plucky inlet
# elfin tree

you make two things here. On one thing, you rotate your object for rotationToApply, on the second line you rotate not just by the rotationApply but also by the current rotation

leaden ice
# elfin tree
quad.transform.rotation *= Quaternion.Euler(0, rotationToApply, 0);```
#

this is what you want if you want to rotate on the y axis by rotationToApply degrees

#

or quad.transform.Rotate(0, rotationToApply, 0, Space.World);

elfin tree
#

And could that work straight on the gameObject instead of on the quads?

#

That's what's weird, first line has no effect

leaden ice
#

i have no idea what that means

#

the quads are GameObjects

#

right?

elfin tree
#

In the code I showed

leaden ice
#

What is "the gameObject"?

elfin tree
#

Yeah they are contained withing the main gameObject lets say

leaden ice
#

and how does that relate to the quads

leaden ice
elfin tree
#

and the 2nd code block iterates on every children (quad) instead

leaden ice
#

Well it depends what you are trying to achieve

elfin tree
elfin tree
leaden ice
#

what are you trying to do?

elfin tree
#

I'm trying to rotate the whole thing haha, so the hallway is aligned once procedurally generated

#

the 2nd code block is a work around for the first line

leaden ice
#

if you want to rotate the whole thing you just rotate the parent

elfin tree
#

yeah which is:

gameObject.transform.Rotate(0, rotationToApply, 0);

leaden ice
#

If that's not working then there's something wrong with your setup

elfin tree
#

okay

leaden ice
#

you'd have to explain the hierarchy

#

which scripts/components are on which objects

#

where this code is running

#

etc

elfin tree
#

Whenever it's done reloading assemblies I'll give it a try

#

But hallway prefab has some quads which represent the walls

#

At the root of the prefab there's the HallwayController code which I showed part of above

#

The prefab is instantiated

#

and then the method which sizes it and rotates it, for example, is called

elfin tree
#

from the room generator

leaden ice
elfin tree
#

like this

leaden ice
#

Share the RoomGenerator and the HallwayController scripts

elfin tree
leaden ice
# elfin tree

recommend changing GameObject hallwayPrefab to HallwayController hallwayPrefab

#

so you don't need to do a GetComponent

elfin tree
#

ohh i see, thanks

leaden ice
#

Still unclear where the rotation is happening

#

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

elfin tree
#

Ah, yeah missing that part

#

If that's still unclear I'll do a hastebin

leaden ice
#

I'd prefer the bin

elfin tree
leaden ice
#

can you share the RoomGenerator too?

elfin tree
leaden ice
#

so what makes you think the rotation isn't working exactly?

#

Can you share a screenshot of the hallway prefab, including its hierarchy and inspector ideally

elfin tree
#

Let's see, so I'll start with testing out what you said earlier

#

I've been waiting on that but I guess it's crashed

#

But it appeared to have no effect yesterday

#

But as you said I was using it the wrong way

plucky inlet
#

I constantly run into unity crashing, especially when using plastic scm open besides Unity editor open.

#

So just force quit and restart

elfin tree
#

(1) is without the rotation command
(2) is with the rotation command

#

gameObject.transform.rotation *= Quaternion.Euler(0, 90, 0);

leaden ice
elfin tree
#

Just to explain what you're seeing, it's two faces of the hallway

#

In the middle

#

You can ignore the rest

leaden ice
#

looks like it's rotated to me

#

notice how the pattern on the wall is different

#

it's a different wall

elfin tree
#

ah ignore the pattern on the wall, it's something different, lemme see if I can remove it

leaden ice
#

withotut he pattern on the wall what else would we be looking at lol

plucky inlet
#

Maybe show your sceneview with gizmos ๐Ÿ˜‰

elfin tree
#

the two faces, basically it's hallway, and it should face towards the hole

leaden ice
#

yeah

elfin tree
#

okay 1sec

plucky inlet
#

And also the inspector and its rotation values

leaden ice
#

this is not a very illustrative image

elfin tree
#

this is what I'm trying to rotate

leaden ice
#

anyway I'm sure you'll find that in the inspector the rotation has changed

leaden ice
#

what is this thing

#

can you show the prefab - and the hierarchy etc

elfin tree
#

yeah it should have 4 but it's messed up lol

leaden ice
#

with the gizmo

elfin tree
leaden ice
#

with and without the rotation

#

also make sure your tool handle rotation is set to local

#

and position to pivot

elfin tree
#

ah it was global

#

(1) is with (2) is without

#

they could be the same images afaik

#

but they are not

plucky inlet
#

And what about the inspector of your rotation?

#

are the rotation values changing at some point?

elfin tree
#

(1) without (2) with

#

i would expect a 90 somewhere if it worked

plucky inlet
#

And the script is on what hierarchy object?

elfin tree
#

root

#

so afaik gameobject.transform (or .whatever) should be the whole thing, no?

plucky inlet
#

gameObject.transform is the root then, yes

elfin tree
#

it's so weird that it wont rotate then

#

and that manually rotating the quads instead works

plucky inlet
#

But you are sure, by adding debug.log before and after setting rotation is doing something?

leaden ice
elfin tree
#

But yes, just let me know what to screenshot

leaden ice
elfin tree
#

Ah

leaden ice
#

I want to see evreything else

elfin tree
plucky inlet
#

Oh boy...

elfin tree
plucky inlet
#

you are checking the values in prefab mode

#

You are not in the running scene! you are in prefab mode ๐Ÿ˜‰

leaden ice
#

ah

#

yes

#

twentacle is correct

#

you should be looking at the instance in the scene

elfin tree
#

The values are the same though

leaden ice
# elfin tree

but in this screenshot you're looking at the prefab

elfin tree
#

I can do the same screenshot in the scene

leaden ice
#

and not an instance that was in the scene already, for example

elfin tree
#

Hmm good point, let me make sure

#

I think it might have to do with that, I made a wrong assumption, it's instantiated twice, so I think it might lose it's rotation at the 2nd instantiation.. will keep testing things

#

Let's say I modify this variable (hallwayX), it wont modify the prefab itself, correct?

#

Yeah that was it, thanks a lot

plucky inlet
hard sparrow
#

Bit of a long shot, but am trying to convert worldposition to hex cubic coordinate. It seems to work fine when converting from cell position to cubic, but not from world to cubic: cs ``` cs
public static Vector3Int WorldToCubic(Vector3 worldPosition)
{
var cubicX = (Sqrt3 / 3f * worldPosition.x - 1f / 3f * worldPosition.y) / CellSizeX;
var cubicY = (2f / 3f * worldPosition.y) / CellSizeX;
var cubicZ = -cubicX - cubicY;

    int cubicXRound = Mathf.RoundToInt(cubicX);
    int cubicYRound = Mathf.RoundToInt(cubicY);
    int cubicZRound = Mathf.RoundToInt(cubicZ);

    var xDiff = Mathf.Abs(cubicXRound - cubicX);
    var yDiff = Mathf.Abs(cubicYRound - cubicY);
    var zDiff = Mathf.Abs(cubicZRound - cubicZ);
    
    if (xDiff > yDiff && xDiff > zDiff)
        cubicXRound = -cubicYRound - cubicZRound;
    else if (yDiff > zDiff)
        cubicYRound = -cubicXRound - cubicZRound;
    else
        cubicZRound = -cubicXRound - cubicYRound;

    Vector3Int cubicCoordinate = new Vector3Int(cubicXRound, cubicYRound, cubicZRound);
    return cubicCoordinate;
}```cs
#

this just gives bad results

tawny elkBOT
#

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

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

!cs

tawny elkBOT
#

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

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

dont type it, use the cs after your three `when pasting code

hard sparrow
#

cs doesn't work

plucky inlet
#

you have to write 3xcs then, your code and 3x again

#

3x `

hard sparrow
#

it just doesn't work lmao

#
public static Vector3Int WorldToCubic(Vector3 worldPosition)
    { 
        var cubicX = (Sqrt3 / 3f * worldPosition.x - 1f / 3f * worldPosition.y) / CellSizeX;
        var cubicY = (2f / 3f * worldPosition.y) / CellSizeX;
        var cubicZ = -cubicX - cubicY;

        int cubicXRound = Mathf.RoundToInt(cubicX);
        int cubicYRound = Mathf.RoundToInt(cubicY);
        int cubicZRound = Mathf.RoundToInt(cubicZ);

        var xDiff = Mathf.Abs(cubicXRound - cubicX);
        var yDiff = Mathf.Abs(cubicYRound - cubicY);
        var zDiff = Mathf.Abs(cubicZRound - cubicZ);
        
        if (xDiff > yDiff && xDiff > zDiff)
            cubicXRound = -cubicYRound - cubicZRound;
        else if (yDiff > zDiff)
            cubicYRound = -cubicXRound - cubicZRound;
        else
            cubicZRound = -cubicXRound - cubicYRound;

        Vector3Int cubicCoordinate = new Vector3Int(cubicXRound, cubicYRound, cubicZRound);
        return cubicCoordinate;
    }```
#

you have to press enter after cs

plucky inlet
#

so, back to your issue. Can you explain with some values, what you expect and what is your result?

hard sparrow
#

specifically the 'pixel to hex' part

#

I even asked chatgpt for code and it gave me the exact same thing I already had lol

#

It's giving wrong values and not even a unique value for every hex

#

Whereas if I go from cell position to cubic coordinate, it comes out just fine

#

Probably no one knows, but figured I would ask

plucky inlet
#

Do you visually display your results so you know, they are wrong?

hard sparrow
#

world to cell to cubic should be correct

#

but world to cell calculation is the most expensive part so

orchid bane
#

How to fly around an object with DOTween?

hard sparrow
#

Hm, I changed it so instead of dividing by cell size, I just multiplied by 2. And now it gives correct values. No clue why that works

#

except it isn't quite perfect... ugh, math

chrome horizon
#

Hello! Has anyone faced this issue were a host build recognises the input system but the client (player2) doesn't recognise it?

private bool IsCurrentDeviceMouse
{
get
{
#if ENABLE_INPUT_SYSTEM
return playerInput.currentControlScheme == "KeyboardMouse";
#else
return false;
#endif
}
}

toxic notch
#

I'm trying to figure out why my array is being modified even though it's not a global. Psuedo code looks like this:

public float[] myArr;

Start() {
 myArr = new float[] { 0, 0, 0, 0, 0 };
}

Update() {
  MyMethod(Vector3 pos, myArr);
}

MyMethod(Vector3 pos, float[] arr) {

  for (int i = 0; i < 5; i++) {
     arr[i] -= number;
  }

}

When I log arr in the beginning of MyMethod() it changes between frames, and I'm not sure why because I'm never modifying it at the property level. Seems like it would just continue to be that initial array of 0s Any ideas?

candid kiln
#

Can i adjust the video length or cut my videoclip inside Unity?

chrome horizon
ionic adder
mellow sigil
candid kiln
toxic notch
#

@chrome horizon It's just psuedo to show I'm modyifing the elements by some value. MyMethod is void

#

@mellow sigil Ahhhhh

#

didnt know they were ref in c#

candid kiln
ionic adder
wary wagon
#

is there a gizmo for displaying text ?

wary wagon
#

ohh thank you !

dense spear
#

Hey guys!! So I am working on a camera system which on start will change the FOV of the camera until all the corners of the plane (which would be the ground) is fully visible to the camera. So if any one of the points are yet to be rendered, it will keep changing the FOV.
I have tried playing with the GeometryUtility and also the Bounds. But I dont exactly know how to use them

Like in the pictures below... Regardless of the FOV value at the starting... it will change the value until the plane looks like the one in the 2nd pic

This is how far I have got

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class TestController : MonoBehaviour
{
    public Camera camera;
    public MeshRenderer renderer;
    
    public Plane[] cameraFrustum;
    public float zoomOutSpeed;

    [Space(20)] [Header("Plane Properties")]
    public GameObject plane;
    public Bounds planeBounds;
    public Collider planeCollider;
    public MeshFilter meshFilter;
    
    [Space(20)] 
    public List<Vector3> verticesList;
    [SerializeField] private int verticesCount;


    private void Start()
    {
        Mesh mesh = meshFilter.mesh;
        planeBounds = mesh.bounds;
        GetCorners();
        
        //StartCoroutine(ZoomOutCam());
    }
    
    
    
    private void Update()
    {
        cameraFrustum = GeometryUtility.CalculateFrustumPlanes(camera);
        
        
        if (!GeometryUtility.TestPlanesAABB(cameraFrustum, planeBounds))
        {
            camera.fieldOfView += Time.deltaTime * zoomOutSpeed;
        }

    }

Can someone help me figure this out please๐Ÿ˜ƒ

Thanks

leaden ice
dense spear
leaden ice
#

yes

#

you would use a target group

dense spear
#

coz... I havent explored Cinemachines much since I have never worked on a top down game before

leaden ice
#

and put empty objects on the corners and use them in the target group

#

Cinemachine is absolutely essential for 99% of Unity games

dense spear
regal marsh
#

I am getting this message periodically and don't know what to do. I have tried updating my drivers (they were all up to date) and I only have one driver so I can't disable it (I tried, it made everything even worse). Any ideas?

#

I know this isn't strictly coding but this seemed like the best place to ask.

simple egret
regal marsh
#

ok

hybrid goblet
#

how can I say that the on destroy function depends on another gameObject and thus it should destroy the other gameObject after it detroys the one with the onDestroy function?

plucky inlet
#

Just call the destroy method on the other object with a delay instead of trying to run code that has been destroyed

hybrid goblet
#

so I need to add a script to that gameObject which has a coroutine in the onDestory function?

plucky inlet
#

For example, an Invoke of destroy with delay or a coroutine, whatever you prefer

hybrid goblet
#

okay thanks, struggeling with interactable trees atm, I need to replace them in runtime and switch them back after, so the scene isn't empty

plucky inlet
#

Do you need to destroy them or could you just disable the gameobject?

hybrid goblet
#

Well I can't do either, I need my terrain, I switch the terrain treedata for an empty array on run time and then want to switch it back to how it was before

plucky inlet
#

Okay, but you can store the treedata, right?

hybrid goblet
#

Yea

#

Oh wait I'm dumb, I'm doing that in a seperate gameObject instead of just attaching the script to the terrain which would prevent it form getting destroyed while running the code

#

Sometimes my stupidity is insane

cyan rapids
#

Hello. Would there be any limitations to or concerns with doing something like this? One issue I ran into is that I can't make a List<Debuff<T>>. My goal is to have all subclasses implment a function that takes itself as a parameter for that function.

public abstract class Debuff<T> where T : Debuff<T>
{
    public abstract void HandleStackAdd(T debuff);
}

public class Poison : Debuff<Poison>
{
    public override void HandleStackAdd(Poison debuff)
    {
        // implementation for Poison...
    }
}
plucky inlet
cyan rapids
#

private List<Debuff<T>> debuffList;
isn't supported unless T is specified

#

it doesn't compile

plucky inlet
#

Could you work with an interface?

cyan rapids
#

I'm not really sure, I generally try to stick to classes. It might also matter that debuff inherits from some other custom classes and it's a whole chain of things

#

I could write the same code in every debuff subclass and handle it there manually, but I figured there has to be a better way of doing it that's more maintainable and generic

hybrid goblet
#

it works

simple egret
#

Well that's because T is defined where you created the list

#

Try outside that class

hybrid goblet
#

didn't want to create new scripts for this, so I just stuck with creating a instance and calling the hi function with:
Poison p = new Poison();
p.hi();
the functioning code:

public abstract class Debuff<T> where T : Debuff<T>
{
    public abstract void HandleStackAdd(T debuff);
    protected List<Debuff<T>> debuffList;

    protected void initDebuffList() {
        debuffList = new List<Debuff<T>>();
    }
}

public class Poison : Debuff<Poison>
{
    public override void HandleStackAdd(Poison debuff)
    {
        // implementation for Poison...
    }

    public void hi() {
        initDebuffList();
        Debug.Log("Hi");
        Debug.Log(debuffList);
    }
}
hybrid goblet
simple egret
#

That's what their issue is about

#

Assuming that list is meant to go on, say a player, where it's not defined

cyan rapids
hybrid goblet
#

I thought he wanted to put it into the abstract class

cyan rapids
#

I think I might've found a better way of structuring it all that might work, I need to test it though

simple egret
#

Maybe you could reverse it all, get rid of the generics entirely and inject your entity into the debuff method

plucky inlet
#

good question about the generics. why do you need debuff to be generic when you Inherit from it anyway?

hybrid goblet
#

true it just goes arround in circles an interface or a pure abstract parent class would be better

plucky inlet
#

if you want to divide by types of a debuff, just use an enum for example or let poison inherit from debuff without generic approaches

cyan rapids
# plucky inlet good question about the generics. why do you need debuff to be generic when you ...

HandleStackAdd() should be called on a an existing debuff if I try to add a new one of the same type, so I can figure out how to combine them on a per-debuff basis, and that is going to need data from that specific debuff type

Basically the way it is now is:

poison = new Poison(value, duration);
poison.AddTo(entity)
[does this entity already have a posion debuff? if so, I don't need to register to events and all that, I can just tell the old debuff to add X stacks and combine values and stuff, so I call HandleAddStack()]

#

but, what I realized is it's kind've weird to have a tag handle a method to add itself to an entity like that? so I'm trying something else with a tag list/tag manager thingy

#

it should work with generics, i just gotta type it out

plucky inlet
#

yeah, just find the enum == the new enum object and if yes, add up

cyan rapids
latent latch
#

I just make my debuff/buff class a non-generic c# class which inits coroutines onto the player mono

cyan rapids
#

that's interesting

#

if i can get this to work I'll try and share my solution :)

crisp bronze
#

Hi, I'm running into this really odd problem. I have this code:

targetObjects[i].DOMove(endPosition.position, durationOffset).(Ease.Linear).SetLoops(-1).OnStepComplete(() => {
                    currentRenderer = targetObjects[i];
                    Debug.Log("Loop1");
                });

The actual loop seems to work just fine, but the code inside of OnStepComplete doesn't run UNLESS only the Debug.Log line is there. It seems that if I add anything else, the OnStepComplete doesn't actually get called. Has anyone experienced this?

plucky inlet
#

so List<debuff> but gettype will return poison if its a inheritance of debuff?

cyan rapids
#

Huh, I didn't really think of that. Does that work like that?

#

I thought if you have a list of debuffs, and get the type of an item in that list, it'll always return as a "debuff"

plucky inlet
#

It works, jsut teste

cyan rapids
#

Wow, that's crazy, I'll try it

plucky inlet
#

gettype of secondlevel which is inheritance of firstlevel prints out secondlevel in a firstlevel list ๐Ÿ™‚

cyan rapids
#

There have been so many times in the past that information would have been useful ๐Ÿ˜…๐Ÿคฃ

#

Thank you

plucky inlet
#

Very welcome ๐Ÿ˜„

mystic ferry
#

I have event triggers on my UI used to call PlayHover() for the OnMouseOver callback, but I'm using a singleton for the audio clips which apparently means the event trigger has a null reference at runtime. How do you guys create global OnMouseOver sound effects?

plucky inlet
tidal shadow
#

i have these variables, filled in inside the inspector as you can see
so why when i set the layer of my gameobjects, do i get the error "A gameobject can only be in one layer. THe layer needs to be in the range [0...31]"?

mellow sigil
#

Layermask is not the same as layer

tidal shadow
#

then what datatype is layer?

#

just int?

#

sortinglayer?

#

oh yeah it is sortinglayer

#

nope, that gives me datatype error

mellow sigil
#

Layers are ints

tidal shadow
#

how do i get it nicely in the inspector, to see the actual layer i set it to?

#

oh wait, i have to follow these numbers right?

soft shard
mystic ferry
#

instantiating things at runtime is so much more modular and clean but oh my god the boilerplate dependency resolutions drive me insane

latent latch
#

Could be a load order issue, so make sure references that are needed after the singleton is created are in Start() or an init/assignment func

mystic ferry
#

good idea

rocky hollow
#

anyone know why unity crashes everytime i run this bit of code? im creating a map generator that generates a grid of tiles first, then a path through the grid that starts on one side and ends on the opposite side. im not sure if the code is even working properly at all as everytime i run the game unity freezes up entirely https://pastebin.com/DtcfHTQr

latent latch
rocky hollow
#

im trying to do that yet i cant seem to find specifically which one is causing the issue/ how to stop it

unkempt sail
#

is there a way to set the transform of an object while keeping in mind its bounds for things like teleportations?

unkempt sail
#

lets say I am doing this teleportation with a ray cast, when I do that the ray cast hit will return a point lets say at a wall, when I this teleportation on the player on what ever object, the object might be into the wall it self

#

how can I still do the teleportation, but not have the object inserted into the wall

unkempt sail
#

this would tell me if the teleportation does happen if the object will be intersecting with other colliders, my question is about moving the transform so it doesn't intersect

hexed pecan
#

Pretty sure you can just use the hit.distance from the sweeptest

rain minnow
unkempt sail
#

does renderer.bounds return maxs and mins based on rotation, or the identity bound?

hexed pecan
#

Did you even try sweeptest..?

unkempt sail
#

yes

hexed pecan
#

If it hits something, move your character towards the direction.normalized multiplied by hit.distance

#

Dont use the hit.point

rain minnow
hexed pecan
#

Its perfect for this use case, unless if I misunderstood what you want

unkempt sail
#

let me try

buoyant mural
#

So I want to check if enemy is facing attack position (the enemy is a plane that drops a bomb) I typed this

            float dot = Vector3.Dot(transform.forward, (destination.position - transform.position).normalized);
            if (dot > 0.7f) { Debug.Log("IS facing"); }

but it only works if X and Y are facing the attack position how can I exclude x position?

hexed pecan
# unkempt sail let me try

I just tested this with a cube and it works flawlesslycs var direction = transform.forward; if (rb.SweepTest(direction, out var hit, 10f)) { Debug.DrawRay(transform.position, direction * hit.distance, Color.cyan, 5f); transform.position = transform.position + direction * hit.distance; }

unkempt sail
#

works great

#

thank you

hexed pecan
unkempt sail
#

this does pose a problem for objects that don't have rigidbodies

hexed pecan
#

You can use CapsuleCast, BoxCast etc. They work similiarly

#

SweepTest is best when you have multiple colliders on one RB

buoyant mural
hexed pecan
#

It basically casts all of the object's colliders towards a direction

buoyant mural
#

Ok I understand

hexed pecan
#

Not much different from the other Cast methods

buoyant mural
#

Yeah

hexed pecan
#

The trick is to use origin + direction * hit.distance not hit.point

buoyant mural
#

Hm

hexed pecan
#

So it takes the collider's volume into account

#

hit.distance is the distance that the collider/rb can move freely

buoyant mural
#

Without colliding?

hexed pecan
#

It moves it to the very point of collision but without overlapping

buoyant mural
#

Oh yeah that's very good

hexed pecan
#

Its useful for sure

buoyant mural
#

Yeah

mystic ferry
#

really strange error here because I'm not destroying anything, and all of my other actions work perfectly fine

buoyant mural
mystic ferry
#

any idea what could possibly cause this?

buoyant mural
mystic ferry
#

when I click on the stack trace it doesn't take me to anything

#

this is so strange

hexed pecan
#

Also is it 2D or 3D

buoyant mural
hexed pecan
#

Okay you could use Vector3.Angle for example

buoyant mural
#

And I do not want it to be exact so if it's off a bit it should still count as facing

hexed pecan
#

Can use Vector2.Angle actually

buoyant mural
#

In a 3D game?

hexed pecan
#

Yes since you only want horizontal rotation right?

#

Left-right

buoyant mural
#

Yes

#

Because if it detects X then the plane is just gonna dive to the attack position

hexed pecan
#

I will show with Vector3 anyway its maybe easier to understand:
-Make a Vector3 that is the plane's forward, but make its Y value zero (so its only on the horizontal plane)
-Make another Vector3 that is the direction from your plane to the target, make this vector's Y zero also
-Check the angle from the first to second vector with Vector3.Angle

buoyant mural
#

Though I think vector2 would be better code

hexed pecan
#

Yep, less extra computation because we only need X and Y (really X and Z)

buoyant mural
#

Yeah I really care about optimization and clean code

hexed pecan
#

You can do the above steps with Vector2, just put the X into X and Z into Y

#

And forget the "set y to zero" parts

buoyant mural
#

Yeah ok will try

buoyant mural
hexed pecan
#

See, Vector3 is easier to understand ๐Ÿ˜†

buoyant mural
#

Well

buoyant mural
hexed pecan
#

Because you only care about the horizontal plane, so you want X and Z

buoyant mural
#

Oh yeah

hexed pecan
#

And if you want to use Vector2 then you need to put the Z into Y

buoyant mural
#

yeah ok

buoyant mural
#

Ik how to do it

hexed pecan
#

targetpos - selfpos

buoyant mural
#

oh oh bro

#

Probably cuz it's 1:45 am lol

#

I think it worked

#

Ok it worked

#

thanks

torn eagle
#

Hey!! I need a hand fixing this code so that it finds a new texture if the resolution is smaller than 256x256

            Texture2D texture = new Texture2D(flower.width, flower.height);
            texture.LoadImage(bytes);
            img.sprite = Sprite.Create(texture, rec, new Vector2(flower.width, flower.height), 1f);
            rt.sizeDelta = new Vector2(flower.width, flower.height);
            texture.Apply();
#

Alternatively, would there be any way to simply upscale the texture if it were smaller than that resolution as doing so via code seemingly clears the texture

quasi terrace
#

Does anyone know why .unitypackages are included in gitignores (or Plastic SCM's ignore.conf)? They are pretty common in assets from the asset store and these assets might not be able to function until you open up the package. Would it be wise to remove it from my ignore.conf so that I can set up plugins across multiple devices (not just the computer I downloaded the asset from) or should it stay the way it is?

cerulean oak
#

how do I set a MeshRenderer material back to the shared material, after having modified its material (and thus having a material isntance)?

#

I tried doing

meshRenderer.materials[0] = meshRenderer.sharedMaterials[0]```
Also tried storing the sharedMaterial before modifying the material, and neither of them worked
hexed pecan
cerulean oak
#

no

#

the material is simply kept as an instance

hexed pecan
#

Oh wait

cerulean oak
#

not using the shared material

hexed pecan
#

materials gives you a copy of the array

#

So you should get it, modify its [0] item, then assign it back

#
var mats = meshRenderer.materials;
mats[0] = meshRenderer.sharedMaterials[0];
meshRenderer.materias = mats;```
#

That should work

hexed pecan
cerulean oak
#

still not working

hexed pecan
#

Are you sure that code is actually running

#

Put a debug log there

cerulean oak
#

it is

#

already checked

hexed pecan
#

Log the materials[0] before and after

cerulean oak
#

ok setting the sharedMaterial as a property and assigning that works

hexed pecan
#

Does it have only 1 material?

#

Im curious if it didnt work because it has 1 mat and you were using the array

cerulean oak
#

yes only one material

#

but using .material didnt seem to work either

cerulean oak
quartz folio
#

why would meshRenderer.material = meshRenderer.sharedMaterial do anything?
Once you have used .material, sharedMaterial is gone, no?

cerulean oak
#

yes, seems like it

hexed pecan
#

Probably because meshRenderer.sharedMaterial doesnt exist anymore after you have overridden it

#

Or returns the .material

quartz folio
#

Exactly, you override it with material, and then that's all it returns

#

material is just a fancy property that checks whether sharedMaterial has been instanced yet, instances if it can, and then swaps it

#

otherwise they're just referring to the same thing

cerulean oak
#

ok now another problem, this was suposed to be a way to improve perfomance but it didnt improve shit

#

xd

#

going to sleep now

#

but for some reaosn having 200 material instances drops the perfomance, but replacing them back with the shared material doesnt recover it?

#

ok it does

#

but for like 2ms

limber agate
#

Im trying to make a inventory system, I have a inventory array that holds all the item data and the imaginary slots, but idk how I can pair the lets say 3rd inventory slot UI with the 2 index in the array. (Also the amount of inventory slots determined till the game is ran)

cerulean oak
#

The UI?

cyan bronze
#

Is there any way to auto clear unused reference in Assembly Definitions? Only through IDE?

neat hollow
#

hiya, I'm getting 'using' related errors even thought theses packages are in the project. could the project have been corrupted somehow? : error CS0246: The type or namespace name 'TMPro' / and 'InputSystems' could not be found (are you missing a using directive or an assembly reference?)

leaden ice
neat hollow
#

in unity unfortunately

leaden ice
# neat hollow in unity unfortunately

Then either:

  • you have spelled something wrong (InputSystems is not a thing for example)
  • you have not installed the appropriate package(s)
  • you are using assembly definition files and have failed to include references to those package assemblies in your assemblies.
neat hollow
#

it could be assembly definitions - I set some up for Testing before, as I have TMP and Input System packages installed and using //using UnityEngine.InputSystem; //using TMPro; at start of script

leaden ice
#

If you are using asmdefs then you need to add references to those assemblies in the asmdef in order to use those assemblies in your code that is inside an assembly

neat hollow
#

...ohHH ๐Ÿ™‚

#

..the only one i can find in scene is just says {
"name": "NewAssembly"
}

leaden ice
#

assembly definitions don't exist in scenes

#

I have no idea what you're looking at

neat hollow
#

ill have to rebuild them - its in my asset folder - watching a tutorial now

leaden ice
#

Assembly Definitions are assets in your asset folder with the .asmdef file extension

neat hollow
#

yes this video explains its well just going throught the steps https://www.youtube.com/watch?v=eovjb5xn8y0&ab_channel=GameDevGuide

The first 1000 people to use the link will get a free trial of Skillshare Premium Membership: https://skl.sh/gamedevguide05211

Learn how to get back into the Editor faster after making changes to your code by using Assembly Definition Files in your project!

Gameplay Logic using Bolt: https://youtu.be/tP9_YBpBBpI
Attributes and Reflection: htt...

โ–ถ Play video
#

..nope still getting same error even thought i added textmeshpro to the definition

neat hollow
#

yes i'm using plastic and saved scene of course - had to role back the changes and will come back to it another day, looks like will take a lot of research to fix. thanks again

leaden ice
#

Not sure how plastic is relevant exactly...

split venture
#

unity is giving me the incorrect answer?? am i using these wrong?

leaden ice
#

and what are you expecting here

split venture
split venture
#

yet im getting 0.35

leaden ice
split venture
#

uhh no idea

leaden ice
#

Mathf.Atan uses radians

leaden ice
#

it's important

split venture
leaden ice
split venture
#

based on my log

leaden ice
#

if you want the same answer on your calculator you should switch to radian mode on your calculator

split venture
#

how do i do that

leaden ice
#

i have no idea

split venture
#

nono i want the same mode

#

on unity

leaden ice
#

i don't have your calculator

split venture
#

as my calculator

#

i want unity to get what my calculator is getting

split venture
#

cheers

granite nimbus
#

is there a more efficient way of converting int3 -> Vector3Int than just new Vector3Int(int3.x, int3.y, int3.z)?

leaden ice
granite nimbus
leaden ice
#

wait if you actually mean efficiency then this will actually be faster since it doesn't call a method:

Vector3Int a = default;
a.x = myInt3.x;
a.y = myInt3.y;
a.z = myInt3.z;```
#

if you want to just make it convenient - make an extension method

leaden ice
#

since it doesn't call a method

granite nimbus
#

oh you edited, ok

hexed pecan
#

Lemme write that down in my micro-optimization notes ๐Ÿ“

granite nimbus
leaden ice
#

they have the same overhead as calling any other method.

granite nimbus
cold parrot
gray zephyr
#

alright alright

#

fellas

#
private bool _active;
public bool Active
{
    get => _active;
}

or

private bool _active;
public bool Active {get => _active;}

or

public bool Active {get;}
leaden ice
#
private bool _active;
public bool Active => _active;```
#

this one

gray zephyr
#

๐Ÿ‘€
I didn't even know that one existed

granite nimbus
wise hollow
#

The shortest one

#

Easy to read and quick to understand.

#

Plus looks good in a wall of code

gray zephyr
gray zephyr
wise hollow
#

Remember kids. The better the code sheet looks the further you will go in ur projects

deft lake
#

Alright so I am working on mouse based movement system for a rhythm game that is a hybrid between audio surf and geometry dash (also intend to add other mechanics from various other existing rhythm games). And the system works great! For the most part that is, see I am running into a issue where sensitivity outside of the editor is much higher than inside the editor, and I cant pinpoint why.

Is it possible you guys might be able to see the problem, or see if it is missing something it probably needs.

This is the script used to handle movement for the player. Dont mind my odd way of organizing the code

gray zephyr
#

before I try to help you
I will not mind but I will question your odd way of organizing codeโ€”good code is self-documenting, comments become clutter

second, try adding cs after your ```

#

it'll make the code highlighted/colored for us to read

#

transforms cannot be instantiated without creating a dummy gameobject I'm pretty sure

#

// This seems to be useless but might be needed, I dont really know since the script works perfectly fine without it for some reason

that's a sign that you should remove it from your code so it isn't cluttered

boreal bone
#

also yeah you don't need it

deft lake
#

I probably should, I still dont know however how the hell it works without grabbing the transform.

boreal bone
#

MonoBehaviour already has a this.transform

leaden ice
gray zephyr
#
    // Start is called before the first frame update
    void Start()
    {
        
    }```

that was added automatically by Unity, but you 100% don't need to keep it
cosmic rain
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.

hexed pecan
#

And most likely the cause for the issue you are describing

#

Also yeah please share the code correctly

deft lake
#

But yeah so removing the deltaTime should fix the issue?

hexed pecan
#

Forces are already multiplied by deltatime by default

deft lake
#

Really?

#

Well thats handy.

gray zephyr
#

mmmmm deltatime squared

hexed pecan
#

Though deltaTime, when called from FixedUpdate, returns the fixedDeltaTime which shouldnt change

#

Remove the multiplication and remember to make your forces about 50x smaller to compensate for that

deft lake
#

The issue persists even after removing them and ajusting the forces.

hexed pecan
leaden ice
#

then using them in fixedupdate

#

since they don't have the same cadence, you will discard many Update frames typically per FixedUpdate

#

to solve this you must accumulate mouse delta in Update

#

and consume it in FixedUpdate

#
Vector2 mouseDiff;

void Update() {
  // accumulate mouse motion
  mouseDiff += new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y");
}

void FixedUpdate() {
  // consume accumulated mouse movement
  Vector2 mouseSpeed = mouseDiff;
  mouseDiff = Vector2.zero;

  // continue
}```
#

For example^

deft lake
#

Maybe I really am not cut out for this if I cant understand how any of "that" works.

leaden ice
#

what are confused about

dim spindle
#

when i start learning something new, i also dont understand how it works

#

but after a lot of using it, I get it, and then I can use it with ease

deft lake
#

I do not like my brain.

dim spindle
#

(this happens ALL the time for me, so dont expect to go without learning new stuff all the time)

leaden ice
dim spindle
leaden ice
#

all it's doing is:

  • in update, we're adding all the mouse movement we see into a variable named mouseDiff
dim spindle
#

when you need to actually design a solution to a new problem, thats when your brain comes into play

leaden ice
#
  • in fixedupdate, we're using all of that accumulated mouse movement to do our motion
#

that's all it is

dim spindle
#

but understanding stuff is 99% just experience

deft lake
#

Oh I see, so instead of just dumping the mouse values straight into fixed update, we compile it all into one variable that wont throw away half the input data.

leaden ice
#

yes

#

exactly

deft lake
#

I will give it a shot. Also thoughts on the rest of the code?

leaden ice
#

otherwise we're forgetting the mouse input from all the frames where there was no FixedUpdate

#

Osmal's comments on deltaTime etc are all correct

deft lake
#

I get it now.

#

Alright well I threw those away, so I just need to do the mouse thingy.

dim spindle
#

i think im doing physics wrong since i have not used fixed update once

#

and i have a player controller

#

and they can throw stuff

deft lake
#

With this I should be able to remove the / 4 value since I dont need it to slow the sensitivty down

dim spindle
#

but its worked so far lol

rocky hollow
#

im trying to make a script to generate a grid of tiles, then generate a path through that. right now though, it crashes unity everytime and gets stuck looping on the switch statement that determines what tiles are a part of what side of the map. anyone know how to fix it? thx https://pastebin.com/ZeSRA0QQ

hexed pecan
dim spindle
#

charactercontroller

#

but throwing stuff is in rigidbody

hexed pecan
#

Ok, as far as I know, CC should be moved in Update

#

So you should be good on that part

#

If by throwing you mean single force impulses, its fine to do from Update too

#

But for continuous forces you wanna go FixedUpdate

dim spindle
#

ok

#

im good then

deft lake
dim spindle
#

thank YOU for taking the time to learn this stuff!

#

๐Ÿ™‚

deft lake
#

Why must I be thanked?

dim spindle
#

a lot of people will just copy and paste and come back 20 seconds later with an issue

#

because they understand nothing about the code

#

people who take the time to learn are much appreciated here, at least by me ๐Ÿ™‚

#

Hopefully by everyone else too!

deft lake
#

I see, well from what I can tell the code takes my mouse inputs and consoldates them into a variable, I still dont understand fully how it works with Vector2

#

dealing with vectors scare me, but I am terrified of quaternions, but future mechanics in my game WILL need them

dim spindle
#

In what way? The vector2 is just for the mouse movements in both directions. you can move your mouse up and down, and you can move your mouse left and right

leaden ice
#

You can just think of that vector2 as two regular floats nicely packed together as one variable

dim spindle
#

those are the two values in the vector, just how much you moved your mouse either way

dim spindle
deft lake
#

Oh I see, so I can just pull both X and Y from mouse speed now?

dim spindle
#

yes technically but why

#

usually you want to keep them together

#

but it depends on what you are doing

deft lake
#

well I have no reason for mouse Y, it is useless for my game at the time being until a add a feature planned for beta. (that being a arcade style flight element)

#

what I am using the mouse inputs for is this code (sorry for the mess)

   
// This set of if statements handles left and right movement of the player
        if (Input.GetAxisRaw("Mouse X") < 0) // Checks to see if mouse input is going Left
        {
            rb.AddForce(Vector3.left * -mouseSpeed * mouseSensitivity); // This applies the mouse speed to the player going leftwards
        }

        if (Input.GetAxisRaw("Mouse X") > 0) // Checks to see if mouse input is going right
        {
            rb.AddForce(Vector3.right * mouseSpeed * mouseSensitivity); // This applies the mouse speed to the player going rightward
        }```
dim spindle
#

please use this formatting guide !code

deft lake
#

See I take the X movement of the mouse, and if a mouse moves left, the player moves left, same goes for right

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.

dim spindle
#

inline code specifically

#

discord has cool builtin formatting for code, makes it very clean to read

#

ah you put the cs on a new line i think?

#

the cs gives it colors lol

deft lake
#

oh alright, i do like my fancy colors

dim spindle
#

tells discord that its C# code

#

Thank you!

deft lake
#

there

dim spindle
#

interesting

deft lake
#

I made it all not so bad looking.

dim spindle
#

so one thing i noticed, why do you take -mouseSpeed in your left branch?

deft lake
#

Its because even though its being told to apply a left force, it reads the -mouseX input and applys that to left causing it to go right

#

Thats a confusing sentence

#

Basically it for some reason applies the negative value going left, which leads to going right, so I had to negative it agian.

#

Negative-Ception

hexed pecan
dim spindle
#

also, i think you can skip the branching with something like this

float direction = mouse_x > 0 ? 1 : -1

and multiply the whole thing by that.
but im not sure if thats desirable over just two bigger branches

deft lake
#

Not sure what branching means.

dim spindle
#

its technically branching but IMO it looks better.

#

like if cases

#

and this provides opportunities for less repeating yourself

mossy vine
#

Do you guys have a link to c# tutorials that break down the structure of it?

dim spindle
#

again not sure its desirable here

rocky hollow
deft lake
#

Im not sure either, I would hate to have to add needless confusion for something that works using simple to understand systems.

#

But yea getting mouse speed is very important, as without the mouseSpeed variable in the code, it causes the mouse when moving left or right to act as arrow keys causing the player to move at a set speed instead of with the mouse, but with mouseSpeed it makes the player move faster the faster you move the mouse

hexed pecan
rocky hollow
#

i know whats wrong with it, not how to fix it. sorry i shouldve been more clear

hexed pecan
#

Where does it get stuck exactly?

dim spindle
rocky hollow
#

it gets stuck repeating the for loop forever. although i literally just fixed that issue by adding a default case, though the path generation does not work and i get an "out of range" error when running the game

deft lake
#

@leaden ice Sorry for the ping, but I would hate to use the code you provided without asking if you are ok with me crediting you in the bug fix help section of the credits.

deft lake
dim spindle
#

What part are you confused about?

deft lake
#

I was wanting to know what the DRY is for and why it is used.

dim spindle
#

It stands for dont repeat yourself, its a concept used in programming because it general makes things easier to change, to read, etc, and is has the added benefit of being easier to read

#

imagine if you wanted to make a function to check if a number is even

#

you could do

bool is_even(int num) {
if (num == 1) return false
if (num == 2) return true
// ... ETC
}
#

but it would be much better if you just went return num % 2 == 0;

#

% is modulo btw, its just the remainder of division

deft lake
#

I see, still somewhat confused, but I get the idea.

#

I will explore the concept later down the line during beta when I refine and rewrite parts of code to be less crunchy.

buoyant crane
deft lake
#

Id rather focus on getting things working with the path of least resistance.

dim spindle
deft lake
#

Ya know, seeing its a prototype and all.

dim spindle
buoyant crane
deft lake
dim spindle
#

imagine if you have repeated code referencing the same variable over and over, and you want to change how the variable is used. maybe you want to split it into two variables? if you repeated the code, you have to go through each repeat and change the code that uses the variable

deft lake
#

Alright, so the goal is to not have to go through multiple lines of code to fix the change.

dim spindle
deft lake
#

Can you provide a example using what I have in my script?

dim spindle
#

again its also a LOT easier to understand when you go back later to read your code and change it

#
float mouse_velocity = Input.GetAxisRaw("Mouse X");
float move_direction = mouse_velocity > 0 ? 1 : -1;
rb.AddForce(Vector3.left * mouse_direction * mouseSensitivity);

this is an example

#

im not sure if this snippet works

#

since i dont have access to your project

#

also not sure why you have mouseSpeed and mouseSensitivty

#

also dont mix caps like i did here, it makes it confusing, i just use snake_case on habit, maybe i should stop lol

#

OOPS i also forgot to add a check at the beginning if its != 0 otherwise it will just try to move always

deft lake
dim spindle
#

OH wait was mouseSpeed that accumulated variable from earlier?

deft lake
#

Yup.

quartz folio
#

If you're converting a delta to a fixed value you should be multiplying by deltaTime

dim spindle
#

this is another example of coding principles, naming your variables clearly so you can understand them again

quartz folio
#

because it's no longer a delta

#

though I suppose it's AddForce, so uh not sure any more

deft lake
#

Since mouseSpeed gets larger the faster you move the mouse, if I add that value into code it allows the speed of the player to increase with the increase in mouse movement speed.

dim spindle
#

I think mouseVelocity makes more sense

deft lake
#

mouseVelocity? I like that

#

makes more sense

dim spindle
#

exactly

#

BUT im not saying you should know all this already

deft lake
#

since speed can mean many things now that I think about it.

dim spindle
#

im just saying this from experience

dim spindle
#

alr im gonna go do something else now but def feel free to ping, it might just take me an extra minute to respond or something, maybe longer if im extra busy idk

deft lake
#

Here, before you go, I am packing the project file into a zip that you can freely download to test and mess around to further inspect how it works to give further feed back, since right now, I am a one man show working on this.

dim spindle
#

ahhh sorry I dont really tend to download other people's projects, not because im not interested, just because it takes a lot of extra effort to get them set up and opened on my machine

#

and if i downloaded a whole lot, it would clutter my drive lol

#

you can record a video maybe, or upload a webgl demo if you know how? it could be worth learning that if you want feedback on controls or something

deft lake
#

Is it all right if I send you a raw build, its fairly small, since it literally looks like this,

dim spindle
#

again im REALLY sorry, im not trying to be rude or anything but with unofficial builds i just have a fear of malicious code NOT SAYING that i dont trust you, just paranoid, i hope you understand

#

i just dont have a workflow that i trust for testing other people's projects

deft lake
#

Wait unity can be used malicously?

#

How the hell does that work.

dim spindle
#

anything you can have code with can be malicious

deft lake
#

I dont even know how to make a game that doesnt erase everything as soon as you exit it.

#

That actually still is a problem I need to address later since Soungates whole premise is based on having a geometry dash style level editor.

dim spindle
#

ok again, im not saying i dont trust you, i just dont trust random executables from paranoia

#

I hope you understand lol

deft lake
#

Since the game is practically ment to be geometry dash, but 3D mixed with riff racer

deft lake
dim spindle
deft lake
dim spindle
#

here isnt really the place to discuss tho

dim spindle
warm wren
dim spindle
#

nope

deft lake
#

Yea so my game is just that, and geometry dash combined for a timing based rhythm game with hazards and levels that just look like eye candy and have cool cineamatograhy.

dim spindle
#

probably because im paranoid

deft lake
#

Because seeing the same 80s stylized rhythm racer for every game got boring for me.

dim spindle
deft lake
#

Run on a track, hit a few procedurlly generated points, and thats it. Super boring.

deft lake
dim spindle
#

if you dont have any more programming questions you can go there instead

deft lake
#

Good point, carry on over there then?

dim spindle
#

sure but i only really have 20 mins left before i want to sleep

blissful whale
#

how would you guys calculate the distance between player and the door to trigger a sprite change?

#

I want the door's sprite to change when player is near it

#

but my brain somehow does not work โ˜ ๏ธ

blissful whale
#

When I get near the door it's sprite will change to this

full scaffold
blissful whale
#

like, around the square I draw?

#

that near

full scaffold
#

Then do exactly that

#

There is a very common unity method that checks for not โ€œdistanceโ€ but overlap, or trigger.

plucky karma
#

I'm in a empty scene and playing this scene still generates garbage allocation - Why? Where is this method being called from?

blissful whale
#

This reply worked, even so thanks

plucky karma
cosmic rain
#

Part of the jobs system

swift falcon
plucky karma
#

There's no game objects too, not even the main camera.

cosmic rain
blissful whale
plucky karma
cosmic rain
blissful whale
swift falcon
#

Or just

if(Vector3.Distance(this.position, player.position) > 3)

๐Ÿคทโ€โ™‚๏ธ

blissful whale
#

alright

plucky karma
swift falcon
#

Do this.transform.position though

#

Same thing for the player, donโ€™t forget the transform part

hexed pecan
plucky karma
#

Are you missing an enclosure?

hexed pecan
#

I wonder what is MyTimerCallback ๐Ÿค”

#

Oh its a Threading thing too. The naming just confused me. Like an example method lol

swift falcon
#

@blissful whale and honestly calculating the distance each frame when you have tons of doors is pretty expensive, so I would personally just use a trigger which is cheaper in this case

blissful whale
#

I will be planning to continue this game's development and add more levels, probably you are right