#archived-code-general

1 messages · Page 58 of 1

leaden ice
#

You need to do yield return currentAnimation if you want to wait for it to finish

woeful spire
#

ah, should've clarified that the coroutine simply starts with teleporting the trail to the startpoint. It could just as well say trail.transform.position = Vector3.zero; or something like that.

#

I'd like to wait as little as possible, not even one frame if possible

leaden ice
woeful spire
#

that's what it's doing. The coroutine I'm referencing just teleports it to the start in the same frame it's called:

protected override IEnumerator AnimateFromTo(int index, Action<int> action)
    {
        Transform from = GetTransformFromIndex(index);
        Transform to = GetTransformFromIndex(index, 1);
        float distance = Vector3.Distance(from.position, to.position);
        float fullTime = distance / speed;
        float elapsedTime = 0;

        while (elapsedTime < fullTime)
        {
            float elapsed01 = elapsedTime / fullTime;

            trail.transform.position = Vector3.Lerp(from.position, to.position, elapsed01);

            yield return null;

            elapsedTime += Time.deltaTime;
        }

        trail.transform.position = to.position;

        action(1);
    }
woeful spire
#

after some further experimenting, it seems that it's due to something else so I'm gonna keep at it for a while...

dawn nebula
#

I have this simple 2D projectile gameobject.

I want to rotate it based on the direction of a vector, aligned through the tail. How do?

#

My ability to harness the power of Quaternions has much to be desired.

hexed pecan
golden vessel
#

Will that condition sound.clip == musicAudioSource.clip be true if they come from different objects in different scenes, but they both come from the same asset?

#

Or should I compare some string related to the clip

leaden ice
#

That is a reference to the asset

#

As long as it's the same asset it's the same reference

mighty granite
#

I'm having a lot of trouble trying to draw a simple line between to canvas elements.. Does anyone know how I could make a line render between two UI elements like shown in this picture with the blue line?

#

I was able to use line renderer for 3d objects to create this in 3d very easily.. but there doesn't seem to be an equivalent to use for 2d canvas..

golden vessel
cosmic rain
#

There's also a unity ui extensions package available on GitHub. I think it has a canvas line renderer component. Google it.

mighty granite
# cosmic rain Either don't use a canvas ui for it, or implement a custom canvas line renderer.

Just seems wild to me that it's not part of the standard library. I think there is another layer to my issue though and that is that I have these objects nested within 2 layers of panels. It seems like Unity only keeps track of a child UI objects relative position to their parent. I suppose all that I really need is the objects position on the screen translated to world coordinates but it seems this relative position is messing up that calculation with the built in Unity functions. Is there a way around this nested UI object issue?

cosmic rain
#

If you just need world position of an element, use transform.position🤷‍♂️

verbal pebble
#

Running into an issue with my grounded checks and jumping in my prototype.

I was originally using the controller.isGrounded() to determine grounding, which wasn't ideal due to its' unreliability, and 'work-arounds' meaning that the player would still slowly slip off sloped surfaces.

I'm now using Raycast.Hit in the isGrounded bool. Problem is that now, it seems to be interfering with jumping, it immediately still finding that the player is grounded and preventing the jump from taking place.

#

I looked around online for a bit, but couldn't quite find anything to solve the issue that I'm having here. Raycast itself is incredibly short (only takes place after the soles on the character's foot and lasts for 0.01f), but it still manages to prevent jumps from happening.

#

Is there any way to disable the raycast checks when jumping takes place to avoid this?

mighty granite
cosmic rain
#

What you see in the inspector is not world space position

#

It's the anchored position afaik.

#

Same as you don't see world position on normal transforms(you see local position)

leaden ice
mighty granite
# cosmic rain It's the anchored position afaik.

So these are the same two UI elements as in the previous images. You can see the two anchoredPositions here and their X coordinates are both 0 and only Y is set (I'm presuming this is the offset y-coordinate within it's parent).

cosmic rain
#

Rect transform extends the regular Transform.

verbal pebble
#

Any idea why my while loop would be freezing the editor?

golden vessel
verbal pebble
golden vessel
#

Cos Time.time is not 0

#

When you start

#

The value you want to check is Time.time-startTime

verbal pebble
#

oh yeah, originally it was time - startofjump

golden vessel
#

where startTime is Time.time at the frame you jumped

mighty granite
#

Time.time will always be iterating up. I think you want to capture an instant of time and compare it with the current time to see how much time has elapsed, if it that is greater than you maxJumpTime, then you could jump

quartz folio
#

you just want an if statement

#

Do not use a while loop unless you want the logic in it to run to completion in one frame, or are yielding inside of it somehow

verbal pebble
#

so the logic is meant to make it so the player will jump higher if space is held, but if i was to use an if loop, that immediately makes the player jump higher regardless if i just tap space or not

leaden ice
#

if is not a loop

verbal pebble
#

if statement, sorry

#

but yeah, in my case a while loop just doesn't trigger at all

leaden ice
#

You need to change how you think about this.. remember update is running once per frame

quartz folio
#

You have a fundamental misunderstanding of how this works

leaden ice
#

You need to think about how things progress and change over time.

quartz folio
#

A while loop will run to completion in one frame. The code inside of it will be looped over continuously until the condition is false. By looped over continuously I mean the code does nothing else until it is done.

verbal pebble
#

ah shit, that explains it then

leaden ice
#

Time does not advance.
Frames are not drawn
Other code does not run, etc.

verbal pebble
#

Could it be run separately, say in an ienumerator?

leaden ice
#

Yes

#

That's the point of a coroutine

verbal pebble
#

I already have one set up to disable ground checks on jump, so yeah

quartz folio
#

Update is already a loop through, a loop that is returned to each frame. So if you just use an if statement it will check that logic each frame and perform it if it's true

verbal pebble
#

It only ever triggers once, and that's even if the space bar is simply pressed as opposed to held over the duration of the jump (though that's likely because i haven't set up a minimum time elapsed in the conditions)

quartz folio
#

and presumably that's because Time.time becomes greater than maxJumpTime

#

which, if maxJumpTime is say, 2, then you have two seconds at the start of your game until you cannot jump again

verbal pebble
#

It might be because it's part of a contained Jump() void, which is then executed in update when the player jumps

verbal pebble
#

yeah, mine's already at a second and a half, so there's plenty of time for it to presumably run multiple times

mighty granite
#

I believe that the new Input System has a way of differentiating "Long Press" from "Short Press" and I think that is what you would want in this scenario

verbal pebble
#

I haven't actually given the new input system much of a shot yet, though I could take a look at it

#

IIRC the old and new input systems can be used interchangably, right?

leaden ice
#

All of this can be solved with a few if statements, bools, and floats in Update

mighty granite
verbal pebble
#

Ah damn, all good

wooden jewel
#

Hello, is there a way not to implement every override method in the child a class, since the child only uses some of them ?

tired forum
#

So I have an airship that I am using physics to move (so that I can have a little more of a floaty feeling). What is the best practice for handling the fact that I can't have a mesh collider w/ a rigidbody and Kinematics ?

#

Should I do it using a second physics scene .. do all the forces over there then translate position movements to the first scene? Or should I go with a compound mesh?

leaden ice
trim heart
#

Helloop
Some one know why my game editor is being activated when I'm supposed to be on the game scene?

#

It makes the testing really difficult
And not only happens with the pause scene button

leaden ice
#

therefore the game is pausing

#

Also you have disabled errors in your console log so you're not seeing them. Notice how errors are toggled off here (you have 4 errors in console in this screenshot)

chilly prawn
#

Hey, so i am working on a 2d game where i've inserted different animations for different combos. I want to change the hitbox for every animation. Is there any other way to do it without having to change it frame by frame?

Note: The attack animations look similar to hollow knight's animations. It's just a white slash animation and that is the hitbox that i want to change.

(edit: Do kindly ping me when replying.)

potent sleet
#

on this though: iirc you only need 2 keyframes for resizing it

pure flint
#

Has anyone uses the "Free Joystick Pack"?

#

I've been trying to flip my sprite with the joystick but I couldnt figure out how

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

trim heart
grave raptor
#

is there a way to make an animation clip set a scriptable object on a script, similar to how you can make it set sprites on the sprite renderer?

grave raptor
#

oh yeah it can take an object, I forgot, thanks

pure flint
wise arch
#

Is there a way to get a prefab from an instanced game object in code?

potent sleet
#

why would a UI question be part of code?

plucky inlet
rancid kindle
#

Oh got it thanks, sorry wasnt sure

swift falcon
#

EditorUtility.DisplayDialog... is there something like it for a windows build?

plucky inlet
swift falcon
plucky inlet
#

There are some third party plugins for that to allow filebrowsing on any platform. I think nativeshare has some option for example

#

There is also Runtime File Browser for free if you want to test it on asset store

swift falcon
#

oh thank you @plucky inlet

mellow sage
#

Hello !
For my last year in my school, I've got a project to do, and I wanted to recreate the Solar system with forces on Unity.

My forces are Speed and Acceleration

public double Vitesse(GameObject planet)
    {
        return Math.Sqrt(Constants.G * Constants.SolarMass / (Vector3.Distance(planet.transform.position, Soleil.transform.position)*10000000));
    }

    public  double Acceleration(GameObject planet, GameObject B)
    {
        return Constants.G * B.GetComponent<Data>().mass / (Vector3.Distance(planet.transform.position, B.transform.position) * Vector3.Distance(planet.transform.position, B.transform.position) * 10000000);
    }

and they are called in a FixedUpdate

Vector3 v = Vector3.Cross(Soleil.transform.position - transform.position, Vector3.up).normalized;

gameObject.GetComponent<Rigidbody>().velocity = (float)Vitesse(gameObject) * Speed * v;

GameObject[] items = GameObject.FindGameObjectsWithTag("SpaceItems");
foreach (GameObject item in items)
{
  if (gameObject != item)
  {

    gameObject.GetComponent<Rigidbody>().velocity += (float)Acceleration(gameObject, item) * Speed * VectorAToB(gameObject, item);
                
  }
}
plucky inlet
mellow sage
#

It seems to work for all my planets, they are rotating around the Sun, and seems also attracted to all planets at the same time (all the solar system is moving in my scene), but now I try to add the Moon to rotate around the Earth, and it seems that it doesn't work

plucky inlet
#

Oh you are working with mass and gravity for each planet if I get this correctly?

mellow sage
mellow sage
#

with white it's better x)

plucky inlet
# mellow sage yup exactly

than you have to alter your Vitesse function to not only take in account of your soleil origin but also the earth being its main attractor

#

your Soleil.transform.position is S, the sun right? but the moon does not rotate around the Sun but the Earth, right?

mellow sage
#

ohh

#

yeah thanks i'll try that !

plucky inlet
#

Physically correct the sun will still attract the moon "at some point", but for the sake of simulation, I do not think you want to calculate that too 😉

mellow sage
#

mmmh because Sun mass is >>> at Earth mass, it makes the moon goes really slow 🤔

plucky inlet
#

I mean looking at it over millions of years, the moon will crash into earth probably one day 😄 but nothing you want to simulate I guess 😉

mellow sage
#

ok ok so I've maybe have a problem somewhere else in my code, because with something that makes the moon's speed affected by the Earth's mass and not the Sun as other planets, the Moon is almost motionless

plucky inlet
#

Well the moon is basically travelling at the same orbit as earth does, cause the sun is of course affecting the moon. but the escape velocity is just too high to like let the moon leave earth. It eventually will one day or the "wobble" will flatten and we meet the moon here 😄 but for now you would have to guarantee, that the moon is copying the earths orbit + the earths attraction

mellow sage
#

ohhhhhhhh you gave me an idea ! I could maybe calculate the escape velocity to make that !

#

I'm gonna look for that, thanks a lot ! :)

plucky inlet
hard tapir
#

Why this works in editor, but in game it has no effect
if (Input.GetKey(KeyCode.Alpha4))
{
_input.cursorLocked = false;
_input.cursorInputForLook = false;
Debug.Log("Cursor unlocked and input for look disabled");
}
else
{
Move();
_input.cursorLocked = true;
_input.cursorInputForLook = true;
Debug.Log("Cursor locked and input for look enabled");
}

#

_input is script in first person asset from Unity technologies

cosmic rain
plain coyote
#

not sure which channel is the best for my question:
but I am having a lot of clipping when I am using my FBX model, it is a 3D model for a real-building, so it is a bit complex, but when I navigate around it, a lot of clipping happens and it is very annoying, any ideas how to stop this?

#

should mention in the editor

cosmic rain
plain coyote
cosmic rain
plain coyote
hard tapir
plain coyote
cosmic rain
cosmic rain
# plain coyote

First, try pressing F to focus on a selected object. If that doesn't help, you can adjust the scene view camera at the top right of the scene view toolbar.

thick plume
#

I have 2 GameObjects on the same layer. Both have a Mesh Collider but when they are on top of each other my code doesn't run.

    void OnTriggerEnter(Collider col)
    {
        Debug.Log("it works!");
    }

    void OnCollisionEnter(Collision col)
    {
        Debug.Log("it works!");
    }

currently the Is Trigger options are turned off on both mesh colliders, but if I turn them both on it still doesn't trigger the code.

mellow sage
#

@thick plume do your GameObjects have a rigidbody ?

thick plume
#

yes

mellow sage
#

and, just to know, if you use a OnCollisionStay ?

thick plume
#

i don't, is it a method?

mellow sage
#

same as OnCollisionEnter

thick plume
#

i see, i don't

mellow sage
#

yeah but, idk if it's possible, but maybe when you start your scene, the GO are already in collision 🤔

thick plume
#

shouldn't it trigger the method when i load the scene then

hard tapir
mellow sage
#

idk at all :/

thick plume
#

i see

cosmic rain
hard tapir
#

When alpha 4 presses then those two bolean become false

cosmic rain
#

Or I assumed that you said that...

hard tapir
#

No, movement works but mouse cursor doesn't

cosmic rain
#

In the build?

hard tapir
#

Yes

#

Simply

#

It works when at the begining I set up cursor lock true and cursor locked to true

#

And in opposite way

#

But when I want to handle that in script then 💥

#

Not working

cosmic rain
#

I really don't understand what the issue is.
I'm also confused if we're talking about play mode or build...

cosmic rain
#

Ok

rugged plume
#

hello fellow unity users, ive become aware of a few different ways to do car physics, and im not sure which one to pursue, there is the sphere method, and the wheel colliders, and im sure there are many other methods.

im trying to recreate the kind of physics from Sega Rally Championship or other Rally type racing game, which one would be better for this?

#

here is a reference for what im talking about

#

theres pretty much no drifting, just angling

potent sleet
potent sleet
#

Another option is to also use Raycasts to kinda create suspensions

rugged plume
#

yeah, that and a few like, arcadey games

potent sleet
#

the Unity Car in standard Assets is a good starter imo

#

you can play and tweak

cosmic rain
#

Damn, I remember that game. And some chopper rescue missions kind of game... What was it called..?🤔

rugged plume
#

is that like

#

wheel colliders?

potent sleet
#

Indeed

potent sleet
rugged plume
#

thanks!!

#

im gonna go check that out

potent sleet
#

they took it down from asset store for this one

#

just open the project and it's the Vehicles scene

neon yarrow
#

Anyone know why Unity is throwing issues related to not finding Editor assemblies during builds, despite the file being clearly located in an Editor subfolder?

Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\InitDreamOS.cs(3,19): error CS0234: The type or namespace name 'Presets' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
hard tapir
#

First you can try using namewhereitis;

#

Or you add assembly

neon yarrow
hard tapir
#

Script which is referenced, where it is

deft timber
#

hey, im having a sequence container with enemies that im instantiating via addressables, the enemies are also marked as addressables, altought they aren't loaded, they just sit in that Sequence Container which is being loaded asynchronuesly. How can i release the memory that the enemy takes when the enemies dies? I guess enemy.ReleaseInstance() when he dies won't work, since I didint load him by addressables?

neon yarrow
#

So the directory of the file causing the issue is Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\. The missing namespace is Presets which is from the UnityEditor namespace.

#

But the point is that scripts under Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\ aren't supposed to be compiled during builds.

#

Because it's inside the Editor subfolder.

hard tapir
weary sapphire
#

anyone got a sec? My coroutine is running way too quickly, and I've got no clue how to fix this. I'm trying to make a simple disolving script, but the coroutine isn't workin as intended, and the object is just vanishing

potent sleet
thorn ravine
#

Hi guys, I'm trying to change item scale to fit bigger character. Item has skinned mesh renderer on it. As of my understanding I need change skinned mesh renderer scale, but it doesn't work. Anybody know how to achieve that? maybe I taking wrong approach?

weary sapphire
# potent sleet you're gonna have to post the script.. don't ask to ask
using System.Collections.Generic;
using UnityEngine;

public class Disolve : MonoBehaviour
{
    //PARAMETERS - For Tuning, usually set in the editor.
    [SerializeField]float disolveTime;
    [SerializeField] Renderer rend;
    Material mat;


    //CACHE - References for readability and/or speed.

    //STATE - Private Instance (Member) Variables
    bool isDisolved = false;
    // Start is called before the first frame update
    void Start()
    {
        Application.targetFrameRate = 60;
        rend = GetComponent<Renderer>();
        mat = rend.material;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha0) && !isDisolved)
        {
            StartCoroutine("DisolveStart");
        }
    }

    IEnumerator DisolveStart()
    {
        float disolveValue = 0;
        while (disolveValue < 1)
        {
            disolveValue += Time.deltaTime;
            mat.SetFloat("_DisolveAmount", disolveValue);
        }
        yield return null;
    }
}
potent sleet
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.

weary sapphire
mellow sigil
#

You don't have any pauses inside the while loop so it just runs to completion in a single frame. The yield return null line should be inside the loop.

thorn ravine
#

Hi guys, I'm trying to change item scale to fit bigger character. Item has skinned mesh renderer on it. As of my understanding I need change skinned mesh renderer scale, but it doesn't work. Anybody know how to achieve that? maybe I taking wrong approach?

thorn ravine
#

Yes

weary sapphire
thorn ravine
potent sleet
# thorn ravine Yes

I don't understand why you need to change the skinned mesh renderer instead of just scaling transforms ?

thorn ravine
potent sleet
#

can you explain maybe the setup ?

#

what do you mean "doesn't work"

thorn ravine
#

Well I have a character, which has script which allow to equip items on it. So script works fine, but now I have another character which is bigger. So I want to be able use same items , but scale them before equipping on bigger avatar.

thorn ravine
potent sleet
thorn ravine
maiden breach
thorn ravine
#

afterwards i tried to set transform on skinned mesh renderer

#

like this

#
                    var addedItemSkinnedMesh = partsInstance.GetComponent<SkinnedMeshRenderer>();

                    addedItemSkinnedMesh.transform.localScale = new Vector3(5, 5, 5);
maiden breach
steady thicket
#

I'm working on a 3D pathfinding system that uses a modified version of the A* algorithm. I'm currently using a custom implementation of a Skip List for the "Open Set". Does anyone have any suggestions or resources about possible better data structures? I've tried a Priority Queue, Sorted List and Sorted Dictionary and they are all varying degrees of slower so I made this skip list but I'm not sure that it is the best option for this sort of thing.

maiden breach
thorn ravine
potent sleet
maiden breach
#

For sure. I'm just doing a cover song lol

thorn ravine
maiden breach
potent sleet
#

You can have a separate script that only deals with scaling just on pickup methods

thorn ravine
maiden breach
#

scale is inherited through the hierarchy

#

also, you don't need to access transform through skinnedmeshrenderer. It exists on GameObject as well

swift falcon
#

Hi, Im looking into using unity for an emulation front end, but theres a couple things that Im not really able to get a clear answer for.
Is it possible to:

  • Open a new window like you can with javafx or similar and send data to and from?
  • Display items in a grid or list based on info pulled from a database (Title, image location, that sort of thing)
  • Create drag and drop behavior and/or a file selection window for files and read those files in runtime?
maiden breach
#

@thorn ravine this isn't enough information. Idk where _addedPartsInstances is being set. Could be an empty array in which case no scaling would happen.

#

should just scale the root item object anyway

thorn ravine
thorn ravine
#

All addedPartsInstances are Initialiazed into avatar object

maiden breach
thorn ravine
#

That's how it looks like in the hierarchy in Play mode

#

So item equipping script works fine, it just the scaling doesn't work

maiden breach
#

really, this should all be as simple as:

Transform anchor;
float scale;

public void OnPickedUp(Transform itemTransform){
  itemTransform.localScale = Vector3.one * scale;
  itemTransform.SetParent(anchor);
  itemTransform.SetLocalPositionAndRotation(Vector3.zero,Quaternion.identity);
}
nova python
#

Why is the max x value 1.23 and min value -0.16 at the edge of the screen where my mouse cursor is

#

Is it due to my screen size?

#

I thought Max would be 1 and min 0 no matter the screen size

humble thistle
rugged plume
#

does anyone know how they pulled off this camera effect?

#

im not sure what they are actually doing

humble thistle
rugged plume
#

maybe, it doesnt seem to be running along a path

humble thistle
#

I personally don't have the experience of doing that however I know it's something that it can do

rugged plume
#

also seems to keep a consistent distance from the centre

humble thistle
#

It looks like it'd just be a circular spine around the car to me tbh. Splines can do some wild stuff

rugged plume
#

ohhh! misunderstood

#

well i mean, like how does it know when to rotate where? thats where im lost

humble thistle
#

You do mean the intro at the start of the race right?
Just making sure I'm on the same page as ya

rugged plume
#

nah just like in general

#

he has a "slide" mechanic present in sega rally

#

and like,

#

it rotates the whole vehicle

#

but like, it doesn't rotate the camera

#

until the turning has adjusted properly

#

watch the gameplay, itll show

humble thistle
#

OH

In cinemachine you can have your camera follow and object, you want it to follow a child object and not the parent then change the transforms of the parent when you want the camera to rotate

#

I had to figure this out for myself in my project I'm working on

#

So when he's doing the drifting he is only changing the transform on the mesh of the object, not the parent and probably has a separate invisible child object on the parent the camera follows

rugged plume
#

well its not really drifting but yeh i get what you mean

humble thistle
#

It's the biggest part of it really, so once you're able to get the mesh rotation separated from the camera rotation you have the freedom to rotate the car however you want with the parent object doing the real turning

#

It's kinda hard to explain but it's two parts, the drifting does slightly rotate the whole object but the mesh needs to turn wayyyyy more

#

So like, I think the best example I can come up with with drifting is
Let's say when your turning your car your mesh is also turned but with a "Drift Multiplier" to it so it turns that much more than when the camera turns

#

It'd be your offset between the rotation of the car and the rotation of the camera

rugged plume
#

wait so id like maybe lerp between the current camera rotation and the rotation of the car more or less

#

that actually

#

makes a lot of sense

humble thistle
#

So you'd have the rotation of your whole game object (rotate the parent) with your input method, then call a function that rotates the child mesh as well with an offset multiplier

#

It probably wouldn't be anything close to perfect but it's a good start

rugged plume
#

okay yeah thats a good solution

humble thistle
#

just make sure you make a separate game object for the mesh that is a child under the parent.
I can't over state how long it took me to understand this

rugged plume
#

ill make sure, ive had that happen before

hard tapir
humble thistle
#

👌 Gl on your project

hard tapir
#

error, can you help me? as you can see when I hold alpha key then cursor locked and input is false, however in game it has no effect. Mouse is still in the middle of the screen(it is its behaviour if cursor locked and iput is true)

cosmic rain
hard tapir
#

here

humble thistle
rugged plume
#

Oh dw, I'm not do8ng drifting

humble thistle
#

Ah gotcha

rugged plume
#

Thank you btw!!

cosmic rain
humble thistle
hard tapir
#

no, that cursor cannot click button

cosmic rain
#

Wat...

hard tapir
#

it is wierd right

humble thistle
#

WaitWut I'm confused I'll let you guys figure it out, I don't wanna cause too many cooks

hard tapir
#

here

cosmic rain
hard tapir
#

manually

cosmic rain
#

What part is supposed to lock the cursor? Do you understand?

hard tapir
#

it works, you can click on button when you disable those variables

cosmic rain
#

What line in your code is responsible for locking/unlocking the cursor?

hard tapir
#

wait

#

those two booleans

#
            {
                _input.cursorLocked = false;
                _input.cursorInputForLook = false;
                Cursor.visible = true;

            }
            else
            {
                _input.cursorLocked = true;
                _input.cursorInputForLook = true;
                Cursor.visible = true;
            }```
cosmic rain
#

Wrong.

hard tapir
#

_input is btw where those booleans are

cosmic rain
#

Why would setting some random bools affect the cursor?

#

What is the unity API for un/locking the cursor?

thin aurora
#

You know Cursor.visible is true for both of those?

humble thistle
#

Yeah I was gonna say

hard tapir
#

yes, so I can see where it is bruh

thin aurora
#

Right

#

So the issue is that the mouse is not properly locked?

#

Pretty sure this is how it works in the editor. You should test it in an actual build

hard tapir
#
{
    public class StarterAssetsInputs : MonoBehaviour
    {
        [Header("Character Input Values")]
        public Vector2 move;
        public Vector2 look;
        public bool jump;
        public bool sprint;

        [Header("Movement Settings")]
        public bool analogMovement;

        [Header("Mouse Cursor Settings")]
        public bool cursorLocked;
        public bool cursorInputForLook;

#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
        public void OnMove(InputValue value)
        {
            MoveInput(value.Get<Vector2>());
        }

        public void OnLook(InputValue value)
        {
            if(cursorInputForLook)
            {
                LookInput(value.Get<Vector2>());
            }
        }

#endif


        public void LookInput(Vector2 newLookDirection)
        {
            look = newLookDirection;
        }


        private void OnApplicationFocus(bool hasFocus)
        {
            SetCursorState(cursorLocked);
        }

        private void SetCursorState(bool newState)
        {
            Cursor.lockState = newState ? CursorLockMode.Locked : CursorLockMode.None;
        }
    }

}```
#

this is where those 2 booleans are

cosmic rain
#

What makes you think they affect anything?

#

I'll ask again, what is the unity api for unlocking the cursor?

hard tapir
#

api?

cosmic rain
#

API. Methods and properties that unity provides for you to use.

hard tapir
#

in that script?

cosmic rain
#

In general

hard tapir
#

SetCursorState()

cosmic rain
#

That's "in this script", not "in general"

deft timber
#

that's your function

humble thistle
#

The api is Cursor.lockState and it looks like he is probably just never actually calling that function from the code he's sent

#

He's just setting a bool

hard tapir
#

wait that the issue

cosmic rain
#

I hoped for them to get there on their own though

hard tapir
#

I wonder where is that function called /..

#

So I have to call that function?

humble thistle
#

No he never called the function that he has to set the lockstate

hard tapir
#

ah

#

im stupid

humble thistle
#

There is code there, it was just never being ran

rustic ember
#

How can I have a script as a variable? It needs to be able to have any script as value not just one class

#

Wait can I just use cs MonoBehavior myScript?

humble thistle
rustic ember
humble thistle
#

Oh just make it a public variable

#

It will show up in the inspector then once it's compiled

leaden ice
rustic ember
leaden ice
#

What will you do with the information of which script is assigned?

thin aurora
leaden ice
#

It's not the same

thin aurora
#

You can go one lower and check for Component, or even Object

leaden ice
#

That's a reference to a particular instance of a script

#

not to the script itself

rustic ember
#

I could write cs PlayerController controller But I need something like this:

AnyScript script``` I need to store a list of monobehavior scripts to add to another object when the scene loads
hard tapir
#

As a hobby

#

Im still student

#

So school is priority

leaden ice
#

instantiate it as a child of the other object

rustic ember
leaden ice
rustic ember
#

Does it matter?

thin aurora
#

Yes

#

Can't you make a generic method?

humble thistle
#

It feels really overly complicated so we're trying to figure out if there is a better solution

thin aurora
#

You know context goes a long way

#

Right now allowing the user to input any script is very confusing

rustic ember
#

What do you mean? I have one object. It can have 50 different behaviours depending on what script is attached to it. I need a way for the player to choose

leaden ice
#
public enum MyEnum {
  A, B, C
}

Dictionary<MyEnum, Type> dict = new() {
  { A, typeof(AClass) },
  { B, typeof(BClass) },
  ... etc.
}

public MyEnum[] componentsToAdd;

void AddStuff() {
  foreach (MyEnum e in componentsToAdd) {
    someObject.AddComponent(dict[e]);
  }
}```
@rustic ember
#

something like this

humble thistle
thin aurora
rustic ember
cosmic rain
stable rivet
rustic ember
maiden breach
#

I'd just use an interface like IRunBehaviour

thin aurora
#

I don't think you're going to have a good experience creating such a decoupled system if you have no idea what an interface is 🙃

leaden ice
rustic ember
thin aurora
rustic ember
cosmic rain
#

What I'd do is use an SO to define the behaviors(some people might be mad about it) and reference them in a list on your object.

rustic ember
cosmic rain
#

Well, you'll just need to implement that part in your code.

maiden breach
#

Add/Remove item from list is analogous to enable/disable monobehavior in the scene

rustic ember
hexed pecan
cosmic rain
thin aurora
#

I assume it's not as organised?

maiden breach
stable rivet
thin aurora
#

Then again, who cares

potent sleet
hexed pecan
#

My SO-based AI graph begs to differ (you can instantiate SO's just like monobehaviours)

#

@thin aurora

thin aurora
#

Never said it not to work 😛

leaden ice
#

and probably add using System;

late lion
#

I think the best way to think of SOs is this:
MonoBehaviour is how we create our own custom component types,
ScriptableObject is how we create our own custom asset types.

There are lots of asset types with logic, like AudioClip, Material, etc...

rustic ember
stable rivet
# potent sleet isn't SO just a fancy POCO, I just treat it kinda like a regular class already

could be, whatever you want. i prefer to keep my SOs as models for immutable data and have separate entities that are exposed to the rest of the app. for instance, i'm currently working on a deckbuilder whereby the SOs are the card as they would be stored using a regular old db. the separate entity can then be manipulated into whatever the user does during the run (i.e upgrades). feels a lot cleaner that way. again that works for this project, but im not terribly opposed to logic creeping into SOs as and when it feels appropriate

#

again though, whatever way works for whatever

thin aurora
#

And as with all c# related things: there are dozens of ways to tackle a problem, and it really does not matter what you do. Just stick to it. This includes ScriptableObjects, however you use them.

hexed pecan
#

All of these use cases make sense 👍 I just don't like the "youre using SO wrong" that I occasionally see

left sable
#

hey, a question here about good practice for code order of execution.

I'm creating a script that executes an attack. When the hitbox gameobject connects with an enemy, it sends that information back to the player. The player then activates its own hitstop function to make the attack connect look dynamic, with slowdown etc.

Currently attack executes through a switch function that checks the current attack state: windup, active frames, recovery.

Is it okay to just have that hitstop/attackconnect function take place in the same switch function as the above? Or should I create a separate "attack connect" function that executes?

Reason is that it's simpler and more readable to keep all the attack logic in the same switch function. But I'm worried that because it's receiving data from a different script (the hitbox gameobject) there might be a delay in execution between the main script and the hitbox object.

steady thicket
buoyant crane
idle flax
#

Hey, I have an issue. My particle collision system only uses callbacks when it collides with itself. The particles collide with objects in the world just fine, but it doesn't send any messages to my script except for when it collides with itself. Here's my collision setup:

#

When I set it to not collide with itself, no collision messages get sent.

steady thicket
# buoyant crane What’s a skip list? If you’re just looking for a data structure that’s the most ...

I think that is what my Priority Queue implementation uses (this is what it looks like: https://paste.ofcode.org/sJp3qM3KKHv7igk3cPShkr) but I'll take a look, maybe mine is just a bad implementation. A Skip List is a neat data structure that does weird probabilistic stuff I'm not 100% sure I understand (wikipedia page: https://en.wikipedia.org/wiki/Skip_list my current implementation of it: https://paste.ofcode.org/mTvbZHAikkVbKDiGrN4Xyf). In my testing my pathfinding is about three times as fast using this implementation of a skip list vs. this implementation of a Priority Queue. I'm hoping maybe there is an even better data structure I could use that is perhaps as much faster than the Skip List as it the Priority Queue.

In computer science, a skip list (or skiplist) is a probabilistic data structure that allows

        O
      
    
    (
    log
    ⁡
    n
    )
  

{\displaystyle {\mathcal {O}}(\log n)}

average complexity for search as well as

    ...
buoyant crane
#

i’ve got to go for now, i’ll take a look at it later

sturdy venture
#

Hey Guys, I've got an issue which has me lost (Pretty sure i'm actually just being blind). I'm raycasting from mouse through camera to hit a Texture3D which i'm then stepping at the hit direction through until it hits a specific value, the latter works perfectly however the raycast direction is completely wrong when the object is not in (0,0,0), It's rotation and camera position dont matter and seem to work flawlessly, heres the important code for it and a little gif too! Like I said i'm pretty sure i'm being a bit of a muppet and missing something!
https://pastebin.com/Y79UeHu6

trim heart
leaden ice
#

it's abundantly clear from your video

#

You have an error happening when you press the jump button

trim heart
#

So how could I fix it?

leaden ice
#

read the error

#

fix the error

trim heart
#

let me check

#

What does "receiver" means?

leaden ice
# trim heart

a receiver is a script or object that will execute the animation event

#

basically it's just saying you have an animation event set up, but no script or function to run the event

#

you either need to:

  • delete the animation event if you don't need it
  • create a receiver script and/or method for it
trim heart
#

I'm using visual scripting

leaden ice
#

you still need receivers for your animation events

#

Did you create the animation event on purpose?

trim heart
#

This is the jump animation:

leaden ice
#

that's not an animation

#

that's code that triggers an animation

trim heart
#

That's the code

leaden ice
#

and it's not relevant

leaden ice
#

Do you know what an animation event is? If not, read this^

#

You probably created an animation event by accident if you aren't sure what they are

trim heart
#

I know them, but why I need one? It was working fine until yesterday

leaden ice
#

in which case you can safely just delete it

leaden ice
trim heart
#

Let me se if there is one

leaden ice
#

there is one

trim heart
#

Well, weird, there was an empty one

leaden ice
#

YEp you probably created it by accident

high violet
#

is there someone who have implemented self play using mlagent toolkit of unity?

trim heart
#

There's another thing, now when the attack animation ends, the jump animation is being set because the grounded variable is being activated, but I don't know why

polar marten
stuck glacier
#

Sort of a general question rather than a specific one, but, is VR game development really that much harder than normal game dev? Like if you're competent making flatscreen games, would starting a VR project be VERY difficult, or would it not be that much harder?

mighty ivy
#

Hi, I created a script that uses a NavMeshSurface. It's exposed in the inspector. After updating unity, it seems like I can't reference anymore a NavMeshSurface component to the NavMeshSurface public object in the script! Any clue why?

leaden ice
mighty ivy
#

That's my script

leaden ice
mighty ivy
#

That's the navmeshsurface (above) and below there's the empty reference to a NavMeshSurface script

#

I can't drag-n-drop the NavMeshSurface into that

#

and I have absolutely no clue why

sturdy venture
mighty ivy
#

it's like they are two different scripts

hexed pecan
#

I think you have two navmesh packages conflicting

leaden ice
#

assuming you have no compile errors etc

mighty ivy
#

as everything

#

it's not a new project, it's been months since I'm working into this, and unless I'm being as stupid as I know I am that's not a beginner problem

polar marten
# left sable hey, a question here about good practice for code order of execution. I'm creat...

the things you think are decoupled are actually strongly coupled. everything should take place in the same function.

there might be a delay in execution between the main script and the hitbox object.
this is a nuanced concern, because there are only very specific circumstances where moving something in frame t can possibly result in a collision / trigger callback executing in frame t. the callback almost always gets called in frame t+1. this is the origin of many people using raycasts to do physics in the same frame, although if they mastered playerloops they wouldn't have to do that

mighty ivy
#

I also get that, and it doesn't give a NullReferenceException when it gets there, so I don't get how that's not working

polar marten
leaden ice
#

What happens when you drag and drop do you get a red X? Or it drops but then still says None

polar marten
#

i assume that's what you mean by a texture3d

sturdy venture
leaden ice
#

basically it seems like you have more than one definition of NavMeshSurface in your project somehow

#

Do you have a NavMesh package in your assets folder or something

#

Also check your package manager - make sure all packages are up to date etc, then delete your library folder and let it get regenerated.

mighty ivy
#

in the assets

#

I uninstalled it fromt he package manager and manually installed it drag and dropping the directory into my asset folder

#

that's because it was giving me some errors when I upgraded unity

#

so... I need to reinstall it via package manager because it is conflicting?

leaden ice
#

install from package manager

polar marten
mighty ivy
#

also the official github page says "drop the files in the assets folder"

leaden ice
#

install it from the package manager

trim heart
#

I have a question, does the navmesh works in 2D?

sturdy venture
mighty ivy
leaden ice
polar marten
#

what is your objective? what is this application?

#

it meshes where as we keep everything in camera no meshes generated!
there is a lot to unpack here which concerns me

sturdy venture
trim heart
polar marten
#

you're near the beginning or middle of this long journey

mighty ivy
polar marten
#

it meshes where as we keep everything in camera no meshes generated!
@sturdy venture for example. the only thing the GPU draws is meshes. so there's no such thing as "in camera no meshes generated." and maybe you mean Mesh, but that still doesn't make sense. you can, or cannot have, a Mesh, and some Meshes are "free" and some are costly. in the micro sense, i think you might misunderstand a lot about mudbun. in the macro sense, it performs extremely well, and isn't that what you care about?

#

but what is your objective? the texture3d, what is it?

#

the video you showed looks like you're clicking at a point cloud of an egg

#

lol

sturdy venture
polar marten
#

VFX graph also accepts a texture3d directly

mighty ivy
polar marten
#

and can render SDFs for you

#

mudbun has an SDF based picker

#

in later versions of unity, you can directly render volumes

polar marten
#

so it sounds like by " its basically all finished now though!" you mean "i am only just getting started"

#

what is the objective? to render tomographic SAR?

#

or some part of a photogrammetry pipeline?

#

anyway if you can express what it is, succinctly, for real, then maybe i can suggest the existing unity features that do this stuff

#

based on the code you are pretty new to unity and C#

#

@sturdy venture

we keep everything in camera
this concerns me specifically because it means you might be trying to author a shader

#

or maybe you wrote some kind of graphics code to render this volume, maybe in plain C# or something

#

and all this stuff already exists

sturdy venture
polar marten
#

they already exist, lots of them

#

what is the idea?

#

there are at least 2 inside unity

sturdy venture
polar marten
#

they definitely do what you need to do

#

you don't know 100% what you need to do yet

#

and there are already tools that do things like picking

#

the bigger picture question is why do this in unity? what is the goal?

#

what is this?

sturdy venture
# polar marten they definitely do what you need to do

Unity has a fair bit of the foundational work required and like I said its just a personal project to extend my own knowledge, I explored existing tools and use some but also wanted to develop some myself to understand the mechanics behind it

polar marten
#

then who's we? what 16GB data file is this?

#

it's not sensitive

#

in a micro sense, it sounds like you are at the beginning of understanding how to do this. in a macro sense, surely people have tried rendering large volumes, even in real time

#

the limit you are talking about isn't meaningful is the punchline, at a micro sense

#

and besides, why wouldn't it be preprocessed?

#

that's why i am asking what the application is

#

you will not need to modify this volume data in real time

#

and if you do, well, you gotta say what the application is

#

if you look into vdb, you'd see that there's mipmapping as a preprocessing step, and also volume aggregation as a strategy that pre-existing things use

left sable
# polar marten the things you think are decoupled are actually strongly coupled. everything sho...

re: everything should take place in the same function. How would you do that when using a separate hitbox gameobject? Currently the hitbox collider is a child gameobject of the primary gameobject which is made active when the entity attacks, and fed data for that specific attack to determine damage etc. OnTriggerEnter is used in the script attached to the hitbox. AFAIK there's no way to use OnTriggerEnter from a different gameobject but I may be wrong.

There's a lot packed into your statement so I'm interested in what a better way would be that would be more strongly decoupled.

I like to have custom shaped hitboxes over raycasts, similar to fighting games where large or small hitboxes are part of the advantages or disadvantages of certain attacks

polar marten
#

to extend my own knowledge
anyway, this is the knowledge.

#

right now it sounds like you are doing something for an architectural firm

#

or in an academic context

#

very very hard to say

late lion
polar marten
sturdy venture
# late lion While doctor finishes his rant, I spotted your issue: ```cs Vector3 rayDirection...

Haha Thankyou, I've actually just rewritten it to remove to remove the needless conversions all together: ``` //Camera to Box ray direction
Vector3 rayDirection = ( hit.point - Camera.main.transform.position).normalized;
Vector3 samplePosition = hit.point;

            var depth = tex.data.depth;
            var width = tex.data.width;
            var height = tex.data.height;
            var stp = 1.0f / depth;
            
            //raycasting till the depth
            for (var i = 0; i < depth; i++)
            {
            //making sample position range from 0 to 1
            var finalPos = transform.InverseTransformPoint(samplePosition) + offset;
            
            //changing coordinate based on resolution of 3D texture
            var scaledCoordinate = new Vector3(finalPos.x * width, finalPos.y * height, finalPos.z * depth);
            
            //Retriving pixel color based on current coordinate
            var c = tex.data.GetPixel((int)scaledCoordinate.x, (int)scaledCoordinate.y, (int)scaledCoordinate.z);
            
                    //if mouse hits certain valid surface inside volume(expect 0 alpha and certain color provided by user)
                    if ( c.r > Math.Max(tex.valueRangeMin, tex.cutValueRangeMin) && c.r < Math.Min(tex.valueRangeMax, tex.cutValueRangeMax))
                    {
                        var worldHitPosition = samplePosition;
                        break;
                      
                    }
                    //Next step,we movin
                    samplePosition += rayDirection * stp;
                    
            }```
polar marten
#

it's tough. there is a lot between here and there. you are limited by how expressive you can be in terms of the rules you are trying to do

#

you also have to look carefully at the unity execution order documentation page

#

to help you understand what is going on

#

in terms of timing

reef compass
#

Hello, I need help,

I exported my 2D game and there is very bad Quality, How can I fix it?

#

Text is Too bad

weak flame
#

set number under 0 to -1 and above 0 to 1. How to do?

west lotus
#

if(num < 0) { num= -1} else{ num = 1}

weak flame
#

isn't there a function in mathf for that, I remember there is but I dont remember the name

weak flame
#

yes

#

thank you

#

how can I detect if a button is not pressed using unity new input system?

west lotus
#

If its not pressed ?

weak flame
#

yes

#

?

granite nimbus
weak flame
#

but I want to check if it is not pressed, not just this frame

soft shard
west lotus
weak flame
granite nimbus
weak flame
#

and for that, I need to check that the player isn't clicking any of the movement buttons(which I read the value from using InputValue)

west lotus
#

Hardcode your byte array feed it into a native one

granite nimbus
#

but it seems like no

soft shard
# weak flame and for that, I need to check that the player isn't clicking any of the movement...

So you could check if the value your reading is 0, or there is also .IsPressed which is similar to a continuous GetKey check, though the "new" input system is best used as events rather than used in Update, so it may make more sense to use .started and .cancelled or as Uri suggested, WasPressedThisFrame and WasReleasedThisFrame, since if it was pressed, you know the key is still down, and if it was released, you know it no longer is

hexed pecan
#

Or if you already have cached values, use those

weak flame
#

its gives me an error...

hexed pecan
#

What's your code and what's the error

weak flame
#

void OnMove(InputValue input){
pressed = input.isPressed;
}

solemn raven
west lotus
hexed pecan
weak flame
#
void OnMove(InputValue input)
{
  pressed = input.isPressed;
  //get the the x axis for the vector2.
  movX = input.Get<Vector2>().x;
  //turn the movX variable into int and then assign that into the variable facing.
  facing = (int) movX;
}

InvalidOperationException: Cannot read value of type 'Single' from composite 'UnityEngine.InputSystem.Composites.Vector2Composite' bound to action 'Player/Move[/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'Vector2')

hexed pecan
leaden ice
weak flame
leaden ice
#

Look at GoUp

#

One of these things is not like the others

hexed pecan
weak flame
#

can you tell why?

#

because before I added the

  pressed = input.isPressed;
``` it all worked
hexed pecan
#

Looks like your axis is not the type you are trying to read it as

leaden ice
#

Doesn't make sense

weak flame
#

why?

leaden ice
#

How do you press a joystick

weak flame
#

ha

#

so on vector3 you can...

#

?

leaden ice
#

No...

#

What are you trying to do with isPressed?

#

What are you trying to detect with that

weak flame
#

try to check if the player is not pressing a button and run a function if it is true.

leaden ice
#

What button

#

If it's a separate button you need a separate input action

weak flame
#

its like a group of buttons

leaden ice
#

Read the vector2

#

Check if its magnitude is 0

weak flame
leaden ice
#
Vector2 vec = input.Get<Vector2>();
pressed= vec.magnitude < 0.1f;``` for example
#

Is this a 2D composite or just a regular axis

#

If 2D then this^.

If regular axis then float

hexed pecan
leaden ice
#

From the screenshot seems it's a 1D axis

weak flame
#

yea

#

but I still need the second axis (for jump)

leaden ice
#

Show your action configuration for Move

weak flame
#

just realized that jump is in another action

leaden ice
weak flame
#

so what should it be?

leaden ice
#

The action should be Action Type: Axis

#

then a 1D axis composite binding

#

You only use Vector2 and 2D composites for two dimensional inputs

weak flame
#

ho didn't know about this, I'm gonna try that

leaden ice
#

and then the code should just be:

movX = input.Get<float>();
pressed = movX != 0;```
tired forum
#

So I have an airship that I am using physics to move (so that I can have a little more of a floaty feeling). What is the best practice for handling the fact that I can't have a mesh collider w/ a rigidbody and Kinematics ?

Should I do it using a second physics scene .. do all the forces over there then translate position movements to the first scene? Or should I go with a compound mesh?

thin frigate
#

Can somebody give me a medium-advanced Unity topic to research while on a long car ride?

thin frigate
heavy hornet
#

I already have some movement in my 3d game, but I want to make it multiplayer... should I just start with a new Project or is there some "easy" way to make it multiplayer? (I tried making it multiplayer, but it didn't really work properly)

maiden breach
light wraith
#

is there a difference between rigidbody.moveRotation() and transform.Rotate()?

light wraith
#

ohhh moveRotation rotates to a rotation and Rotate() rotates the entire object?

leaden ice
#

well yes

#

but

#

that's only oone part of it

#

MoveRotation cues up for the Rigidbody to be rotated in the physics engine during the next physics simulation step. If it's kinematic it will realistically push objects out of the way.

transform.Rotate() immediately rotates the object directly, without any regard for the physics simulation

light wraith
#

Interesting, is there any MoveRotation alternative to characterController or transform?

#

kind of a dumb questions since it depends on the physics, I can probably just rotate on fixedUpdate

swift falcon
#

Does anyone have any experience using a neo4j database with unity?

olive summit
#

so the [SearchContext] attribute doesn't get inherited. Do I essentially need to make my own attribute if I want it inherited rather than just using Unity's attribute?

leaden ice
simple egret
zinc merlin
#

guys what's the current best dependency injection library for Unity? I've heard of Zenject/Extenject but it's no longer maintained so I'm not comfortable to start a new project with it.

cold parrot
zinc merlin
urban gust
#

Hey guys im starting to look at Architecture for Unity and trying to make the code clean, i'm searching for Interfaces, Inheritance and Script Composition, and i'm seeing that for example : Damageable(Composition) would be better than the IDamageable(Interface), because of not repeating code with interfaces. So basically want to know if i'm going the right way (?)

violet field
#

Hi, does anyone has the script to a 2D press jump (press longer for a longer jump) like Super Mario

leaden ice
#

But your example is not composition

#

it's inheritance

#

I recommend making Damageable a completely separate component

ember wedge
#

My player isnt teleporting button press and doesnt get teleported all the way

hexed pecan
solemn raven
#

hi ,
does anyone knows how LoadSceneAsync works ?? how does it use the "scene Name" to get the scene and load it ?

leaden ice
solemn raven
#

EditorBuildSettings.scenes is an array of EditorBuildSettingsScene which u can get something called "guid" and "path" from

#

path is the file path

#

not sure what GUID is

leaden ice
#

this is editor stuff

#

what are you trying to do

solemn raven
#

im trying to add/modify scenes in EditorBuildSettings.scenes and also load them on the same script.

solemn raven
#

is the scene's file name is exactly the "scene name" ?

solemn raven
#

what is the scene name ?
example if we have " Assets/Scene2.unity " does that mean the scene name ="Scene2" ?

leaden ice
#

yes

solemn raven
#

I could cut that from the path if that is the only way around

solemn raven
stable rivet
solemn raven
#

how did i miss that 😄 , thanks

stable rivet
# solemn raven Thanks 🙂

I mean, it's alright - but the docs you yourself posted are literally 2 sentences long, and contain the answer 😄

solemn raven
jade nexus
#

how do game developers make a game use a Newtonian physics system

supple canopy
#

I'm looking for a script that automatically creates an animation clip that swaps the material of an object's Skinned Mesh Renderer slot to a selected material.

Does anyone know how to do this, I'm new to c# coding, but kinda know how to read the code & have done a bit in python & java

jaunty needle
#

How would I go about creating an infinitely scalable grid like the one desmos has? I'm trying to recreate it but I'm stuck on that part.

tawny mesa
#

Hey, according to unity profiler "Destroy cull results" takes a lot of time in my game, what it is related to? And how to optimilize it?

neon plank
#

Why point is (0, 0, 0) but there is a collider (i.e: there was a hit)? 🤔
I'm using Physics.CapsuleCastNonAlloc and it returned an integer greater than 0, so the first hit should have some point.

zinc parrot
#

If I have a script that has "using UnityEngine.Rendering.HighDefinition;"
how do I make it so that this doesnt cause errors if im not in HDRP without commenting it out or anything manually?

neon plank
late lion
zinc parrot
#

it would need to be like a #define kind of thing yeah...
I just want to be able to include this file in my project, but not have it throw errors if its not in HDRP

leaden ice
zinc parrot
#

lookin at that right now but it needse to stop the entire file from compiling

neon plank
somber nacelle
zinc parrot
#

alright! thanks! I will try that!

uncut tundra
#

Why is unity giving this error Assets\Scripts\Weapon.cs(98,3): error CS0246: The type or namespace name 'IEnumerator' could not be found (are you missing a using directive or an assembly reference?)

somber nacelle
uncut tundra
#

ok

leaden ice
faint scroll
#

how do i translate a vector relative to another vector like this? (increasing the distance, but not the angle)

stable rivet
leaden ice
faint scroll
#

is the order of points essential?

leaden ice
#

yes

faint scroll
#

so the location of these points matter?

#

i dont know how to explain

#

like in a 2-1 != 1-2 kind of matter

#

ok i solved it

#

thx

leaden ice
#

the location doesn't matter

solemn raven
#

Hey,
if I want to attach a reference to a Scene file in a class "scene.unity" how do i do that ?
like for example string type references can be stored by something like this public string txt

#

GameObject ?

#

Scene?

leaden ice
#

it's been discussed to death

#

the best ways are all hacks around basically just storing a string

#

there's no drag and drop scene references

solemn raven
leaden ice
solemn raven
#

is there is a way around through the editor maybe , that is what iam thinking

faint scroll
#

how do i randomize the location of C to the left/right from B where the location should lay on the perpendicular line of AB?

leaden ice
# faint scroll
Vector3 aToB = (B - A).normalized;
Vector3 offsetDir = Quaternion.Euler(0, 0, 90) * aToB;
Vector3 result = B = (offsetDir * Random.Range(-maxDistance, maxDistance));```
#

something like this

#

assuming we're looking at the x/y plane in the image

faint scroll
#

hm i have another problem

#

i suck at maths lol D:

#

i get B by getting Camera.main.ScreenToWorldPoint(Input.mousePosition)
but it should always be the same distance from A, because i use a line renderer to connect them, but i dont get it to work

#

i tried (Camera.main.ScreenToWorldPoint(Input.mousePosition) - A).normalized; but it didnt work

leaden ice
#

show your code

#

explain what you expect to happen

#

and show what is happening instead

faint scroll
#

it gave wrong results, wait

leaden ice
#

Camera.main.ScreenToWorldPoint(Input.mousePosition) is going to give a point with the wrong z coordinate usually btw

#

you need to either give it a depth or set the Z of the result

faint scroll
#

yes i handled that

#

BlaBla-new Vector3(0, 0, Camera.main.ScreenToWorldPoint(Input.mousePosition).z)

grizzled needle
#

Is there any way that I can shorten this?

    _level.time = parameters.levelTime;
else
    Debug.LogError("RunParameters.levelTime is null, cannot set parameter");```
grizzled needle
#

I have 8 other variables and counting that I need to set like this, so I'm looking to see if there's a better way already

#

if not, then 🤷‍♀️ i'll just go ahead and copy and paste lol

leaden ice
#

or put them in a collection

#

and use a loop

grizzled needle
faint scroll
#

so point A is transform.position
B is Camera.main.Screen....

i want to draw a line from A going to B with a fixed length.

#

because as of right now, it draws from A to B, which later outputs wrong results when messing with the line

leaden ice
#

What do you do with BlaBla

faint scroll
#

eliminate z issue

leaden ice
#

but you're now using a position with x and y as 0?

faint scroll
faint scroll
#

oh wait

leaden ice
#

why not just:

Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
point.z = 0;```
#

faster, clearer, definitely correct.

faint scroll
#

i just realised this too xD

faint scroll
faint scroll
#
Vector3 Cam = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Cam.z = 0;
Vector3 end = (Cam - transform.position);
CreateLine(/*color*/Color.red, /*width*/0.05f, /*start*/transform.position, /*end*/end, /*lifetime*/20);
faint scroll
#

set up a lineRenderer

#

that code works fine

leaden ice
#

Vector3 end = (Cam - transform.position); is getting the direction from A to B

#

not the position of B

#

If you want start and end that's just transform.position and Cam

faint scroll
#

yes, thats why i asked what i should do

leaden ice
#

wdym

#
CreateLine(/*color*/Color.red, /*width*/0.05f, /*start*/transform.position, /*end*/Cam, /*lifetime*/20);```
#

Pass in start and end, as your comments imply^

faint scroll
#

i want to return a point with a fixed distance to a, no matter where ypo click but still on the line between A and the Clicked Coordinates

tepid river
#

normalize and multiply with distance

faint scroll
#

and add A?

surreal garden
#

For some reason my game screen is not visible and my scale is unknown

faint scroll
#

saw this on SO:

var distance = dist;
var direction = (hit.point - startPos).normalized;
endPos = startPos + direction * distance;
surreal garden
faint scroll
#

well it does work now, but only if the initial distance is above the wanted distance.

leaden ice
# faint scroll

The code I shared you way back when you assked the question will do that

faint scroll
leaden ice
faint scroll
#

same issue like i said

#

works only if the initial distance is above the wanted distance

leaden ice
#

it should work no matter what

leaden ice
#

It works for any distance

leaden ice
leaden ice
# faint scroll

this looks like you're not properly zeroing out the z axis

#

so it's going into or out of the screen

#

or your origin point is not at z = 0

faint scroll
#

A is the red square (start)
B is the end of the line (mouse position)
If i draw the lines, it works fine as long as my mouse position doesnt go below a certain value

leaden ice
#

show the object positions

faint scroll
#

ooo

#

z position seems to be off w8

#

approved

#

it works finally

#

thank you very much

broken herald
#

At my wit's end here.... I have a windows il2cpp build that crashes right after the splash screen. The player.log file doesn't show any stack trace. Everything works fine in the editor.

Have you guys ever seen builds crash with no stack trace?

leaden ice
#

a straight to desktop crash

#

or a "freeze until it's not responding" crash

solemn raven
#

I'm trying to understand a conditional function, let me know if I get it right

string test(string txt){
return string.IsNullOrEmpty(txt) ? null : "someResponse";
}

the above statment is equivlant to

if(string.IsNullOrEmpty(txt)) return "someResponse";
else return null;

correct ?

leaden ice
#

you have the if and else backwards

#

it's truevalue : falsevalue

solemn raven
faint brook
#

what would be the most efficient way of getting all the game objects with a tag under a certain parent?

#

so far i just check every object with the tag and then see if its parent is the watned one but i fear down the line this will cuase preformance issues

leaden ice
fluid lily
#

Hey, is anyone else having errors happen when the inspector is in Debug mode? I am using unity 2022.2.0b16 and trying to debug a UI button not being able to be hovered over(aka background image not changing color) after being clicked once, but the inspector is freaking out, and tons of InvalidOperationException: The operation is not possible when moved past all properties (Next returned false) errors.

leaden ice
#

you're on an old beta version

#

there's 2022.2.10 (non beta)

fluid lily
#

Yeah gonna try that first

#

It has been solid so far so haven't needed to update

#

At least it definitely seems to be an editor error and not my code, so will do a bug report if this doesn't fix it. Though those take months in my experience to go anywhere 😭

#

Those this button bug is driving me crazy. If I select out of the player and back in the button works fine again.

tall lagoon
#

hey guys Im trying to make 2D Building system for my game and im trying to make it grid based so things snapso should i use the grid that unity uses like a gameobject with a grid compoenent or should i code the grid fromscratch??
Also how would i get things to snap to the grid?

copper shoal
#

nvm, misunderstood the question

tall lagoon
#

ok

#

ill be here for your suggestions

copper shoal
tall lagoon
#

ok thanks

#

ima check it out

copper shoal
#

I'm trying to make a script that gives my player some velocity in the opposite direction of the spikes he touches ( so they bounce off the spikes). My spikes are on a tilemap and use tilemap collider + composite collider. When I try to use Collider.GetContact(0).point, Unity doesn't really likes that and for some reason it places the point of connection somewhere in the space. How else can I make a script like this?

#

This was supposed to be a Debug.DrawLine between the player collider and the spike collider.

copper shoal
#
        {
            Vector2 direction = (new Vector2 (transform.position.x, transform.position.y) - collision.Getcontact(0).point);
            Debug.DrawLine(transform.position, direction);
            rb.velocity = direction * TrapKnockback;
        }
```]
leaden ice
#

Also the spike collider is the overall Tilemap collider

faint brook
leaden ice
#

Why?

#

It needs two positions

#

Not a position and a direction

copper shoal
#

I'll fix it

leaden ice
#

Also the contact has a normal

#

You don't need to calculate anything with positions

#

You should use the contact normal

copper shoal
#

Okay, it shows correctly now

copper shoal
#

collision.contacts[0].normal?

leaden ice
#

Also it's more efficient to do collision.GetContact(0)

#

it doesn't have to copy the whole array that way

copper shoal
#

so should I use collision.contacts[0].normal or collision.GetContact(0)?

leaden ice
#

collision.GetContact(0) replaces collision.contacts[0]

copper shoal
cerulean mist
#

anyone know how I can align a particle sub emitter normal with the normal of a collided object

steady thicket
#

If anyone has any suggestions of data structures that could be good for the "Open Set" of an A* pathfinding algorithm I would really appreciate suggestions. I've been trying a lot of things and so far the best thing I have found is my implementation of a Skip List. Also, if anyone knows anything about Skip Lists I would love feedback about my implementation as I didn't know anything about them before today lol.

Here is my current Skip List implementation: https://paste.ofcode.org/wT3X8ykCDeHEFstP3cEyPW

velvet quartz
#

What is better use a audio clip on audiosource component or use AudioSource.PlayClipAtPoint ?

potent sleet
#

In what context ?

#

Why not PlayOneShot

hexed pecan
#

This is kinda expensive just for playing a sound

ember wedge
#

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

ember wedge
#

What are backquotes

deft pike
#

hey everyone, does anyone have an idea on how to check if the player is following us on social media ? (in order to give them an achievement for each social). Do I need the user to login to each social to check that ? is there a easier way of doing so ?

deft pike
ember wedge
#

'

dim spindle
ember wedge
#

ook

dim spindle
velvet quartz
#

and PlayOneShot need audiosource component

hexed pecan
velvet quartz
#

So i need to put a audio source on all character

hexed pecan
#

Why not?

#

You can also make your own audio manager that pools audiosources

#

Or use some audio middleware like FMOD/WWise but that's different

solemn raven
#

is it possible to serialize public data as readonly in the inspector only ?

#

like i wanna be able to modify a string from another script public string txt
but I dont want it to be available for me to modify the value of txt from the editor, just read it , is that possible ?

#

readonly blocks the other script from modifying the variable ... so it doesnt work in this case.

serene lake
#

I need to use 2d pathfinding in my game, is there any way to do it without the asset store or simulating it somewhere else?

mystic ferry
serene lake
#

I just didn't want to purchase a $30 package for something small

mystic ferry
#

iirc there are several A* packages for free

serene lake
#

Also I have more complex shapes than cubes and capsules for navmesh

#

How would I get those to work?

mystic ferry
#

depends on what package you’re using, tinker around with whatever you find, it’s likely quicker than writing one from scratch

solemn raven
#

thanks a lot 🙂
i moved on and now im in a bit bigger problem 😄

#

im trying to add items that i have on a list<> to an array

dusk apex
#

Maybe consider using Lists instead of arrays if the size of the collection needs to change often.

solemn raven
#

is it possible to add items on a list to an array ?
as far as i know array can only be defined in the following way

array = [list[0],list[1]....];

but I dont know how many items on the list

solemn raven
dusk apex
#
int[] iArray = new int[iList.Count];```
dusk apex
quartz folio
#

iList.ToArray() will create a new array from a list

#

but it will have to allocate it

solemn raven
quartz folio
#

I have no idea what the API looks like

solemn raven
solemn raven
dusk apex
#

ToArray would return you a copy of the List. If you're wanting a copy of it, that'd be what ToArray does.

carmine pine
#

why cant i move the gameobject?

quartz folio
#

Because you've frozen the object.

carmine pine
#

or is it -=

quartz folio
#

Sure, but that's not assignment if that's what you're trying to do

carmine pine
#

ik

solemn raven
carmine pine
#

is this correct?

dusk apex
quartz folio
#

What you have added is pointless

carmine pine
#

why doesnt it work?

quartz folio
#

Because you never unfreeze the object.

carmine pine
#

oh you need to unfreeze it?

quartz folio
#

Of course

carmine pine
#

my b

#

how do i do that

quartz folio
#

Look through RigidbodyConstraints2D and apply the obvious one

carmine pine
#

how do i assign not equal?

quartz folio
#

You don't. You assign what you intend to assign

carmine pine
mystic ferry
#

oh my god

carmine pine
#

idk how to optimize it

#

and i dont care

#

also its not working how i wanted to and now im sad

dusk apex
#

What're you trying to do?

boreal condor
#

I have a question, I want to modify an Animator State Machine's motion, is there a way to do this? All the information i've found is outdated or the code doesn't work as it was found, there are new APIs it seems but documentation links are dead apparently...
This is the field I'm trying to modify

leaden ice
quartz folio
# carmine pine idk how to optimize it

any time you set .constraints it sets the value completely.
If you want to combine two things use |
Like .constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;

#

this is also completely redundant as it's covered by the fact it's an else to those two conditions

wispy wolf
#

I have a rigidbody that eventually collides with a simple sphere collider. If this hit normal points a certain direction I want this rigidbody to stop moving. This is easy enough. But if the normal is a different value I want to add an impulse to repel it while maintaining its momentum. The problem I have is that once the rigidbody's collider hits the sphere it stops, so in the case of the added impulse all the existing momentum is gone.

leaden ice
solemn raven
#

hey, Im facing an odd problem
I think list get corrupted after deleting an item of it on the editor (inspector)

I have a custom class the holds info of the scene objects , its NAME , COunt in the scene and GUID

once i delete one of the items from the list on the inspector and try to load it again the list get corrupted
i looped through it , the name is correct , the count is correct but the GUID of all item became " 0000000000000000000000000" what is going on ?

#

I think I ran into a bug this time...

#

unity 2021.3.5f1

#

i debuged the list before and after modifying the list guid certainly goes to zero and also some references became NULL! , it wasnt null before

solemn raven
#

hey,
How to assign List<customClass> without it being a reference to the original List<customClass>?

#

i wanna try making a temp list and use it for reference instead

prime sinew
static crown
#

Heyo, I want to keep adding torque to an object every .1 seconds while a key is held down. Would a coroutine be best for this purpose?

dusk apex
inner relic
#

Hi, I'm using the unity starter asset first person controller. I'm trying to add my own input into the starterassetsinput script, but it doesn't work the way I'm intending. I'm trying to have events fire once, but when I press the key, it fires for every frame the key is pressed. How would I change this

#

I already know about buttons and events

#

like started

#

and cancelled

static crown
inner relic
#

but the thing is the unity first person controller doesn't use that, and I don't want to refactor the code