#archived-code-general

1 messages ยท Page 29 of 1

woeful leaf
#

(Through the event)

dreamy light
#

If you have a Top down 30 degree camera following a character in game. And you want the camera to lock it's rotation even when the character changes it's rotation; you can either unparent it from the character and set the location of the camera to the location of the player. Or you can keep it as a child, and set the camera's rotation on update.
My issue, is that I want to rotate the camera around the character while the character is moving (rotating).
I'm using RotateAround
transform.RotateAround(MainPlayerCharacter_Reference.transform.position, Vector3.up, -targetAngle);
The way I see how I would go about doing this would be:

  1. Unparented camera - Get location of character and offset it somehow while the camera is rotating, so that it stays locked to the player while moving.
  2. Parented camera - Get the Y rotation in euler angles of the player character, and subtract it from the camera's rotation, so that the camera can rotate around the character freely while keeping it's position locked on the character.
    Don't really get how to do 1, and 2 is super buggy to convert Quaternion to Euler and back it seems. Any help on this would be much appreciated.
rapid brook
#

Hello, I'm not sure if I'm on the right channel, if not feel free to redirect me.

I'm trying to convert 3D models to pixel art, I'm using a render texture to display the model with a low resolution (my RT is of size 64x64).
So far everything is working except that I now, made a system that generate a texture, and allow my to draw on it, this texture should be applied to the generated spritesheet created from the RT.

To map my texture, I made a vertex shader that set the colors of the vertices, given their positions in the world, where x -> black to red, y -> black to green, z -> black to blue, it gives me a color space in a 3 dimensional space. Once it's done I look up each pixels of the texture I want to apply, and compare them with each pixel of the generated spritessheet frames, if the color matches I apply the color pixel from my texture.

Now the problem is that the render texture doesn't always display the exact colors of the pixels I'm trying to apply, if my spriteSheet is animated, it blends some colors instead of displaying either on or the other, so my question is, is there a way to make my render texture display the exact colors of the model and not have them blended?

#

if you look at the face, and the symbol drawn on the torso, it looks jittery, and I feel like it's caused by the render texture blending in two pixels, if you need more informations let my know

#

A better version of the end result :

whole yew
#

thanks

#

I have another issue where I have a text over a button and the button isnt being pressed because of the text in the way. Is there a way to make it so the click goes through the text?

lusty zephyr
#

I'm creating a top-down 2D game and trying to create a shotgun. It was not quite succesfull on this point. I only have the script to spawn 10 bullets, but they spawn in the players rotation, what's good, but is there an easy way to spread the bullets in a random range of (-10,10)?

{
  Instantiate(normalBullet, basicSpawn.transform.position, basicSpawn.transform.rotation);
}

Since I can't find a good tuto for 2D who has this and you can't sum or sub Quaternion vars, do I have no idea how to create it.

leaden ice
lusty zephyr
#

Oh really thanks! I was searching at this for 2 hours.

shut quail
#

how do i lerp emission color change? This is not working

#

the lerp for material1 is workig but for material2 not

potent sleet
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.

shut quail
#

i did now

#

there is no error

#

it's changing to the material2.color at the beginning but then stays at it

shut quail
potent sleet
shut quail
#

ah i figured it out. I am lerping the emission color with the basecolor but the basecolor isn't lerped that's why it's not changing

potent sleet
#

was about to say

shut quail
#

when i changed it to material1.color it worked because the first should actually change the basecolor

#

ya thanks

whole yew
#

what is a good line limit to have per script?

oblique spear
#

so i know the basic OnCollisionEnter and -Exit methods. The character controller doesnt trigger that according to the docs. How can i detect in a script of a gameobject when the player "collides". From the player sides there is the OnControllerColliderHit() method but i want to check from the other gameobject

tight ice
#

Can someone please tell me why I am getting an object instance error?

My Script (The script that creates the error): https://pastebin.com/jZkntN8c
The script I'm trying to use the "AddMesh" function from: https://pastebin.com/UDPtFQKg

Error: NullReferenceException: Object reference not set to an instance of an object
WaterVolume.WaterVolume.AddMesh (UnityEngine.GameObject obj) (at Assets/WaterVolume/Scripts/WaterVolume.cs:240)
doggo.Start () (at Assets/WaterVolume/doggo.cs:12)

It does print "Added" from the addmesh function, but then gives the error

rapid brook
#

the gameObject you pass in the function is probably null, do a Debug.Log on your gameObject

main shuttle
tight ice
plucky inlet
#

Its GameObject.Find("Plane2"), right?

tight ice
plucky inlet
#

You should check against null if you use Find (which you should not if possible), is it null maybe?

tight ice
#

oh

plucky inlet
#

Fast, before we throw that code command! ๐Ÿ˜„

rapid brook
#

your meshCache is initialized in the awake method and you call the function in the start method

#

the start Method is always called after the awake method iirc which means your meshCache isn't initialized before you call that method

plucky inlet
#

your wv is null Id say

tight ice
# plucky inlet your wv is null Id say

okay so I changed Start() to Awake() and also did a check if WV is null. It says it is null! But how could that be fixed? I need to use the AddMesh function from that script.

plucky inlet
tight ice
#

Ohhh
Edit: Fixed, thanks for the help :D!

plucky inlet
#

Not sure the class you are using is meant to be created at runtime multiple times, but thats something for you to test ๐Ÿ˜‰

rapid brook
#

there would be an instance if it didn't

plucky inlet
rapid brook
#

and instead of wv = new WaterVolume.WaterVolume(); you want to use GetComponent<>() to get the reference of that script

#

any of you could help me for a Render Texture by any means?

plucky inlet
rapid brook
#

I did

plucky inlet
#

where? I guess I missed it then

rapid brook
#

scroll up a little, there is a gif with a multi colored character, that's my post

plucky inlet
#

Oh, you want to have the opposite of anti aliasing here, right?

rapid brook
#

Well yes, in my Rendertexture I configured the anti aliasing to be none

#

yet some colors still blend

plucky inlet
#

I guess you have to step the colors to match your color palette

rapid brook
#

what do you mean by step?

plucky inlet
#

like a step node, where you separate a vector 1 range to a defined step. so for example a color value of 255 gets "stepped" into 16 steps instead.

#

But this really depends on your colors tho. If you allow any colors, its impossible to clamp the values in any handleable way

#

The problem is, the downsizing already does what you want. you cant guarantee a pixel to be a color. Or does your texture look different from the rendertexture?

rapid brook
#

yeah I figured, I tried to create the color space for each part of my model individually but it gives, just slightly better results if any

#

even if that pixel is a Color32? so it's defined between integers of 0-255 instead of a float of 0 - 1

plucky inlet
#

0-1 is still floats, so that wont change much I guess.

#

Your downsize will decide, like seen in the face, if its black or not, thats all you get no matter the actual steps. Thats the downside of downsizing vs "real" pixel art

rapid brook
#

no yeah I meant that I went from Color to Color32 to restrict the color range a little

plucky inlet
#

Your best bet here would be, do not use 1 pixel lines in your design

#

The less resolution you got, the less details you should add, and that face and icon on the middle is just too much for 64x64

shut quail
#

how can i set a fix emission intensity? When lerping the emissions color it always changes too

rapid brook
#

definetly, but I feel like there is a way to do that, isn't there just a way to prevent a render texture from blending the colors? just gives either one or the other color, even if it displaces the pixels, I'd be fine with that

plucky inlet
#

or up the contrast or or or

rapid brook
#

but that wouldn't influence the render texture would it?

plucky inlet
#

Something is showing your render texture, right? That component should be able to hold a material?

rapid brook
#

I guess you are right

#

what if I also added a 3 dimensionnal grey scale when computing the color for each vertex?

#

as far as I'm concerned white and black aren't showing that much, if at all on this model

plucky inlet
rapid brook
#

Like so, I simply have a vertex shader, I encapsulate the bounds of every renderers in my model and then evaluate the lerped value of a worldPoint given the min and max bounds

#

I used 3 different gradients to represent the 3 position axis because I wanted to see if there was a better color set that RGB

plucky inlet
#

Okay, understand that code part. so you could just lerp from black to white to get greyscale here, right?

rapid brook
#

yep

#

the thing is, among all the colors that the vertices will display, there is a lot of colors that are not used because no vertices get these coordinates

#

I might wanna use that

plucky inlet
rapid brook
#

nope here is a quick drawing to make it clear :

#

Maybe I can try to use those colors to make the difference between the colors more pronounced

plucky inlet
severe maple
#

how can I get the mouse position while cursor is locked. Nothing online ๐Ÿ˜ฆ

plucky inlet
severe maple
#

not while cursor locked is on no

rapid brook
#

if the cursor is locked your cusor is always placed at the center of your window

plucky inlet
#

Oh, well, than you gotta get the delta vector, what input system?

severe maple
#

i can get the delta, but how can i get the mouse position from that? Im using the mouse position to compare and get angle from a UI element

plucky inlet
#

How would the UI behave. Depending on your mouse or just like the rotation of your camera?

severe maple
#

lol I will explain. Its a first person game so the cursor is hidden/locked, but when you interact with someone a radial menu comes up. And i want the selected option on that menu to be in the direction of where the mouse is. actually i guess I could use delta tbh

rapid brook
#

but delta will always be Vector2.zero

#

if your mouse is locked

severe maple
#

Oh, i should just unlock it but keep hidden

#

brain fart

stable rivet
#

Anyone have any experience with VContainer? ๐Ÿฅฒ

elder palm
elder palm
#

np

rapid brook
#

seems like putting a greyScale is working better, it still didn't finish to create all the frames but I'll wait and see

vague slate
#

Is there a way to clear RenderTexture without camera?
My game literally has only UI

#

UI toolkit

plucky inlet
vague slate
#

without any cleanup

plucky inlet
vague slate
#

my UI is drawn with UITK

plucky inlet
#

So why not just use a camera with nothing to see in clear flags, so its empty but still rendering?

vague slate
#

what clear flags?

plucky inlet
#

Might be culling mask in whatever render pipeline you are

#

yeah

vague slate
#

do I pick nothing or everything?

plucky inlet
#

nothing

vague slate
#

ah yeah, it has tooltip

#

thanks

plucky inlet
#

yw ๐Ÿ™‚

maiden inlet
#

How do i typecheck an asset?

if (assetType is GenericScriptableTypeRef)
{ do stuff }```

rider tells me the expression is never true
#

what am i missing

simple egret
#

GetMainAssetTypeAtPath returns Type, so you need to check like this

if (assetType == typeof(GenericScriptableTypeRef))

If there was an instance of GenericScriptableTypeRef in that variable, it would have worked with is.

maiden inlet
#

ah ok but my problem is that the assetTypes i want to process inherit from GenericScriptableTypeRef. typeof does an exact typecheck which would always be false.

simple egret
#

Ah, time to whip out some Reflection then, typeof(GenericScriptableRef).IsAssignableFrom(assetType)

maiden inlet
#

thank you! exactly what i needed

void basalt
#

Is it possible to get an animation's exact state, send the data over a network and recreate the pose exactly?

#

I've been trying to figure out how to accomplish this, especially when the animations are blended

lyric wadi
#

when I tried it you had to send multiple states

#

you get multiple states from the animator

void basalt
#

Does each blended animation have it's own "time" as well?

lyric wadi
#

yeah

void basalt
#

Ok cool

void basalt
#

@lyric wadiHow do you go about actually reconstructing the animation on the server though?

#

something like this?

#

I wonder if you can just send the state hash of the animator instead then...

lyric wadi
#

trying to remember it was a couple years ago

void basalt
#

no worries

arctic lintel
#

I'm starting with localization and I need to do this, but with script... how can I do this?

oblique spoke
prime rose
#

hi yall, I'm having an issue with setting the screen resolution/windowed mode - these functions are both being called from dropdown menus, and I've confirmed that the relevant functions/switch cases are being called (at least in editor).

#
public void SetResolution(int resolutionIndex)
        {
            _resolutionIndex = resolutionIndex;
            Debug.Log("Setting Resolution");
            Screen.SetResolution(_resolutions[_resolutionIndex].width, _resolutions[_resolutionIndex].height, _currentFullscreenMode);
        }
        public void SetFullscreenMode(int index)
        {
            switch (index)
            {
                case 0:
                    _currentFullscreenMode = FullScreenMode.ExclusiveFullScreen;
                    break;
                case 1:
                    _currentFullscreenMode = FullScreenMode.FullScreenWindow;
                    Screen.fullScreen = false;
                    break;
                case 2:
                    _currentFullscreenMode = FullScreenMode.Windowed;
                    Screen.fullScreen = false;
                    break;
            }
            Screen.SetResolution(_resolutions[_resolutionIndex].width, _resolutions[_resolutionIndex].height, _currentFullscreenMode);
        }
#

I'm not really sure what I could be missing - nothing at all seems to happen in build

cosmic rain
subtle herald
cosmic rain
subtle herald
#

Cool, then here we go. ๐Ÿ˜„

#

Here's a video of what my below script produces. I'm trying to add roll to my player/camera along the z axis (which... works lol) but not entirely.
It seems the orientation of the x and y axes are locked or something which makes movement very difficult if the current value for the z axis is anything other than zero. Any ideas or advice on how to fix this would be greatly appreciated.

Here's my camera movement script.

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

public class MouseLook : MonoBehaviour
{
    [SerializeField] private Vector2 sensitivity;
    [Tooltip("The rotation acceleration, in degrees / second")]
    [SerializeField] private Vector2 acceleration;
    [SerializeField] private float zAcceleration;
    [Tooltip("The period to wait until resetting the input value. Set this as low as possible, without encountering stuttering")]
    [SerializeField] private float inputLagPeriod;

    private Vector3 rotation; // The current rotation, in degrees
    private Vector3 velocity; // The current rotation velocity, in degrees
    private Vector2 lastInputEvent; // The last received non-zero input value
    private float inputLagTimer; // The time since the last received non-zero input value

    private Vector2 GetInput()
    {
        // Add to the lag timer
        inputLagTimer += Time.deltaTime;

        // Get the input vector. This can be changed to work with the new input system or even touch controls
        Vector2 input = new Vector2(
            Input.GetAxis("Mouse X"),
            Input.GetAxis("Mouse Y")
        );

        if ((Mathf.Approximately(0, input.x) && Mathf.Approximately(0, input.y)) == false || inputLagTimer >= inputLagPeriod)
        {
            lastInputEvent = input;
            inputLagTimer = 0;
        }

        return lastInputEvent;
    }

    private void Update()
    {
        // The wanted velocity is the current input scaled by the sensitivity
        // This is also the maximum velocity
        Vector2 wantedVelocity = GetInput() * sensitivity;

        // Calculate new rotation
        velocity = new Vector3(
            Mathf.MoveTowards(velocity.x, wantedVelocity.x, acceleration.x * Time.deltaTime),
            Mathf.MoveTowards(velocity.y, wantedVelocity.y, acceleration.y * Time.deltaTime),
            velocity.z
        );

        rotation += velocity * Time.deltaTime;

        // Check for "q" and "e" inputs
        float zInput = 0f;
        if (Input.GetKey(KeyCode.Q))
        {
            zInput = 1f;
        }
        if (Input.GetKey(KeyCode.E))
        {
            zInput = -1f;
        }

        velocity.z = Mathf.MoveTowards(velocity.z, zInput * zAcceleration, zAcceleration * Time.deltaTime);
        rotation.z += velocity.z * Time.deltaTime;

        // Convert the rotation to euler angles
        transform.localEulerAngles = new Vector3(rotation.y, rotation.x, rotation.z);

        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        transform.position += transform.forward * vertical * 0.5f;
        transform.position += transform.right * horizontal * 0.5f;
    }
}
tawny jewel
#

hey, so maybe im looking in wrong places but i honestly cant find a proper solution, so basically i have a bird gameobject, and a wing gameobject as its child. i basically just want for wing animation to play when i press space and for the bird animation to play when the bool is set to true. i have a seperate script with settriggers etc. so basically now what do i put where, because putting animator and animatorscript components to both of them separately simply breaks the whole bird

woeful leaf
#

Hey I'm using some code to create text and I rescale it's bounding box, but for some reason it's not scaling it from the center.

            box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
            text.rectTransform.sizeDelta = new Vector2(text.rectTransform.sizeDelta.x + 40.22f, 40.22f * 2f);
            box.size = new Vector2(text.rectTransform.sizeDelta.x, 40.22f);
#

But the pivot is by default on 0.5, so it should scale it from the center

#

And if I do it manually through the inspector, it does scale it from the center, so I'm no sure why the code doesn't and what I can do to fix that

dense cypress
#

howdy, may i request some consultation and guideness from the unity experts

swift falcon
#

sure

#

I'm also going to ask my question

#

how can I implement move_and_slide with navagent as in godot?

#

key being the this-normal*this.dot(normal) line

#

don't really understand the math here

dense cypress
#

its c++ so theres use of pointers i dont know if you probably already knew that

swift falcon
swift falcon
dense cypress
#

roger roger, i sugg at maff

#

looks like it takes the normal and multiplies it by the dot product (could be totally wrong ahah)

swift falcon
#

yes that is literally what it does

dense cypress
#

i cant help sorry ๐Ÿ˜ฆ

#

any one else?

#

i dont wanna post something an block your question so ill wait

swift falcon
#

no go ahead

dense cypress
#

i have a tile perlin world and im generating a minimap using setpixel and using ongui. ive got it to generate the world and move with the player but the minimap just wraps and doesnt generate the rest of the world like the world generating code. i think i just dont understand and am trying to force something that cant generate like that computationally quickly. updating it in the update method just chokes hard

swift falcon
#

seems kinda vague?

dense cypress
#

it just tears and repeats rather than constantly generating

#

sorry i am kinda a noob

#

vague will be my lack of experience in what to even explain cos i dont know enough to know exactly whats wrong xD

swift falcon
#

"doesn't generate the rest of the world" you mean it only generates, e.g. coords within (-100, -100) (100,100)?

compact verge
#

I'm used to working with a 2021 version of unity, but a friend invited me to work on 2022 unity, and it seems a few things have changed. I can't find how you bake a navmesh in this version, There should be a "bake" tab at the top, but it isn't there.

#

I'm used to it looking something like this

#

With a bake and object tab as well

dense cypress
compact verge
dense cypress
#

rather than wrap around it should continue to generate the next coordinates

compact verge
#

Add tab doesn't add anything useful

woeful leaf
#

Ah well then I don't know, sorry

#

Try googling it ยฏ_(ใƒ„)_/ยฏ

swift falcon
#

@compact verge I don't think you need to bake

compact verge
compact verge
swift falcon
#

sec

#

booting my project

dense cypress
#

shall i paste the whole code block?

swift falcon
woeful leaf
#

Pastesite if it's too big

#

Probably

#

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

swift falcon
#

worldSize?

dense cypress
#

changing that doesnt seem to matter i get the same result

#

ive tried moving things around, in start and update etc but it always does this

#

u can see the tearing where it repeats

swift falcon
#

That doesn't seem to be wrapping oke?

#

Are you sure it is?

compact verge
#

But ig unity removed that

dense cypress
swift falcon
#

hm? com.unity.ai.navigation is the new stuff, not the old

dense cypress
#

this + cross section just repeats

#

its visible if i move

#

its the same image tiled infinitely xD

#

im trying to get it to just keep drawing based on the new x and y

swift falcon
#

I guess I just don't know the math

dense cypress
#

it might be a limitation with setpixel and ongui but i cant figure it out

#

then i gotta think of alternatives

#

but ive seen it in say shadergraph, i can scroll through a 2d perlin noise map quite easily

#

infinite procedural yadayada

swift falcon
#

Is there at least a way I can get the next frame step of a navmeshagent and decide whether I want to do it or not?

atomic bone
#

I want to load assets dynamically at runtime
Any recommended plugins for it?

swift falcon
#

ewww apparently navmeshagents will autobreak 100-0 once they hit their target

#

even if they have poor acceleration

#

disgusting

devout wigeon
#

For anyone familiar with LeanTween, is there a clean way to pass a LTDescr as an argument? I thought I was on the right track with my current implementation, but I'm getting some unexpected results. When opening the panel, the animation will play the first time and never again. Closing the panel doesn't seem to do anything. If I use the default tween, opening and closing both work fine.

wispy wolf
#

@devout wigeon I had that problem with LeanTween and it isn't related to your code because I wasn't using it that way. I never found a good answer and just switched to DOTween

devout wigeon
#

Hmm. Well, that's not a good sign. I'm still going to do a bit more digging before giving up because I'm in pretty deep with LeanTween.

fading comet
#

I'm building a simple FPS style character and finally got jumping to work properly where the player can't move in midair. When I land, though, my current movement resets instantly, e.g. if I'm falling sideways and hold w, when I land I'll instantly stop moving sideways and immediately go forward. How should I make this a gradual de/acceleration when I land?
cC is my character controller.

if (cC.isGrounded) { // Only able to move while touching the ground

  move = transform.rotation * (new Vector3( // Get inputs
    Input.GetAxis("Horizontal"),
    0, 
    Input.GetAxis("Vertical")
  ));

  if (Input.GetButton("Jump")) movementY = jumpSpeed; // Jump
  else movementY = 0;

} else movementY -= gravity * Time.deltaTime; // Fall when in the air
move.y = movementY;
cC.Move(move * Time.deltaTime);
devout wigeon
leaden ice
#

and have your input affect the momentum gradually instead of instantly

#

might be easier to just use a Rigidbody based controller at that point since it has velocity built in

wispy wolf
#

Hang loose for a minute.

devout wigeon
wispy wolf
#

Their APIs are very similar but the terminology is just different enough to trip you up

devout wigeon
wispy wolf
#

I like LT but after that bug popped up and I couldn't figure it out I figured it is worth it to just bail instead of wasting more time. All tween libraries are similar enough that its easy to move over.

devout wigeon
compact verge
#

Whenever I try to open any windows in unity, it doesn't open. I'm trying to open preferences, but after countless attempts it still doesn't do anything when I click on it. None of the other windows open either. I've tried closing and opening unity and it still doesn't work. This problem only occurs on my laptop (which I'm using right now) but not on my PC for some reason. Any help would be appreciated.

potent glade
#

ok i have two problems , the first is that I made a linux server build, the application.quit ISN'T working.. I am using System.Diagnostics.Process.GetCurrentProcess().Kill();
I want to know would that cause a problem to my game or would there be a risk of anything??

warm wren
potent glade
#

my 2nd problem is with unity webgl builds... I am using the Application.OpenURL("https://..."); and it is also not working... can osmeone help me

stable osprey
#

also aren't you missing a " in the end?

#

(just wanna make sure it's pseudocode lol)

potent glade
#

no no I am sure I didn't miss the other " in my code

stable osprey
#

just type Application.OpenURL(..) next time :p

#

Application.OpenURL should work in WebGL, BUT

#

you'd be better off using javascript, with Application.ExternalEval

rare tendon
#

can someone help me? Microphone.devices is empty, and I cant figure out why. unity audio is NOT disabled, ive triple checked

stable osprey
#

Application.ExternalEval("window.open('http://www.google.com');");

rare tendon
#

not a web gl build

potent glade
rare tendon
#

its a unity class

potent glade
#

oh

rare tendon
#

it lets you access the system microphone

stable osprey
#

ah, never heard of it.. I'd use the system classes if available

rare tendon
#

cant, needs to be cross platform

potent glade
stable osprey
#

mind you should add the #IF UNITY_WEBGL preprocessor to it

potent glade
#

it is saying it is obsolete ... what should I look for to make this work without using obsolete classes

stable osprey
#

in PC builds, you'd rather use the OpenURL

stable osprey
#

just maybe not open it in new tab (but maybe they fixed this from what I read)

#

so maybe it's your ad blocker settings?

potent glade
potent glade
rare tendon
#

yep already did

#

unchecked

stable osprey
#

@potent glade can I see your code?

#

you actually include the https:// part, right?

potent glade
#

just a second

#

if you dont mind we're going to do 1 test in 10 mins... I put a debug text...i will make sure that the condition leading to goign to the other webpage is happening

stable osprey
#

sure yeah

#

but just found out that OpenURL now doesn't work in an old project in which it used to

#

tried in both chrome, firefox, and msedge

potent glade
#

i am reading the link now

#

thank you

stable osprey
#

yw

stable osprey
rare tendon
#

windows is fine

#

i have multiple devices available, most should be free

stable osprey
#

um.. restart the editor? ๐Ÿ˜„

rare tendon
#

thats what im gonna try next

stable osprey
#

I wanted to suggest enabling the 'allow apps to take control of this device' option, but since unity accessed it it should already be enabled -- wouldn't hurt to double check though

rare tendon
#

no go

#

restart time

#

i should also clarify, im not looking for a specific device, i jsut want any devices at all

#

that did something!

#

no longer telling me theres no mic

#

now the editor crashes

#

ima try agian jsut to confirm

#

OK

#

mic is now detected

#

idk wtf that was, but thank you for your help

stable osprey
#

np lol

stable osprey
rare tendon
#

hmm, interesting

stable osprey
#

I assume the built-in Microphone class is not a very popular API, so yeah I'd be reluctant to go with it either way

rare tendon
#

i need a cross platform way tio detect if the mic is above a certain level

#

it cant override unity audio like fmod

stable osprey
#

I've seen a number of voice-related APIs in many languages or whatnot, so if you don't care about WebGL might wanna go for it

#

alright

slow crag
#

Any idea why this is happening?

novel raven
#

im trying to write a function to open audio files from a .zip file
i have this code that makes a DeflateStream that presumable contains the data, but i dont know how to convert it to an audioClip

public AudioClip LoadAudioFromZip(string zipFilePath, string audioFileName)
    {
        // Open the zip file
        using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
        {
            // Find the audio file in the zip archive
            ZipArchiveEntry audioFileEntry = archive.GetEntry(audioFileName);

            // Check if the audio file was found
            if (audioFileEntry == null)
            {
                Debug.LogError("Audio file not found in zip archive: " + audioFileName);
                return null;
            }
            Debug.Log(audioFileEntry.Name);
            Debug.Log(audioFileEntry.Open());
            // Convert to Audioclip?
            
        }
    }
worthy timber
#

i want to make a 2d tower defense game, but how can i make my turret target the first enemy? i have no idea, i don't need code but help to understand the algorithm

#

the range of the turret is a 2d circle collider (trigger)

novel raven
worthy timber
#

of the turret

potent glade
#

in my webgl app the fullscreen button wont work.. any idea why that might be

worthy timber
#

i could do that a faster enemy is a priority but that could cause problems

#

for example it will ignore other enemies that are closer to my base

novel raven
#

they you will need to make a function to sort the list of enemies, i presume your enemies are traveling along a list of points?

worthy timber
#

the enemies will follow a path made of a list of positions or something like that

#

but if i need to sort the list, how can i make the faster enemy place in his current "location" and not too low or high in the list

novel raven
#

sort enemies by their target point, then sub sort by their distance from that point

worthy timber
#

that's smart

#

thank you!

worthy timber
#

i have not watched that video but maybe it could help you

novel raven
#

Its different because a .zip gives me a Stream not just raw file data

worthy timber
novel raven
#

im using them for voiceover/subtitle data, so the .zip will have hundreds of soundclips so having them stored as open data would be less efficient

worthy timber
#

yes, you are right

thin aurora
# slow crag

This is your editor giving a warning, not Unity

#

So this code is fine

#

Your editor is just clueless about it

#

I'm sure it can be supressed somehow

slow crag
#

I see. Is there something I can do to guarantee my async method is awaited before Update() is called?

#

I don't think there is without some hacky workarounds like disabilng the object

thin aurora
#

Idk what UniTaskVoid is

#

But Unity is not gonna wait for an async method before calling the next tick

#

So If you specifically want an async method to finish before calling the next Update, the actual update method should check if the method finished

#

Cause I can't find UnitaskVoid

#

So you should check if it returns anything but pending, and then you should handle the result should it have faulted

#

This is how it works with actual Tasks anyway

slow crag
#

yeah, I'm just doing this for now:

private async UniTaskVoid Start()
    {
        // Disable Update() until all the managers are initialized
        enabled = false;
        DefManager = new DefManager();
        await DefManager.LoadDefs();

        InitializeManagers();
        StartNewGame();
    }
slow crag
thin aurora
#

Give me 1 sec and I'll give an example on what I mean once I get back to my pc

slow crag
#

I'm pretty sure I understand what you meant but it doesn't feel as good as this "workaround"

woeful leaf
#

How can I make it so I can scale this from the center within the code? The pivot is already 0.5 but adjusting the sizeDelta within the code doesn't scale it from the center

#

I need it to be bigger because the IDragHandler ignores BoxColliders

#

If I can make the IDragHandler unignore BoxColliders, that'd work too. But you probably can't really do that

plucky inlet
#

Good morning everyone. Is it possible to switch or if statement over a generic T value? I am trying to have one function handling different lists. So I want to pass in json data, the target list and also the type. Can I get the type from the target list or just use a third param to pass in the desired type?

        private void RecievedDataHandle<T>(string data, List<T> targetList) where T: JsonAttributes
        {
            var Object = JsonConvert.DeserializeObject<CMSJson>(data);

            if (Object != null)
                foreach (var d in Object.data)
                    if (d != null)
                    {
                        ///Switch here somehow to get myDesiredType
                        targetList.Add(d.myDesiredType as T);
                    }
        }
woeful leaf
plucky inlet
nimble dome
#

Can anyone help me with this?
I have a class that contains a list called itemData whose values are defined in the inspector. On a separate script I want to have a dropdown in the inspector that lets you select one of the values contained in the itemData list from the previous class. How do i go about doing that?

woeful leaf
plucky inlet
trail sinew
#

how do I stop the cineamchine camera dragging behind my camera

woeful leaf
trail sinew
#

oh ok

orchid bane
#

How do I make a separate tile have some functionality? Like the question mark tiles from mario, when you hit them with your head from the bottom, they spawn a mushroom at the top of themselves and the tile's sprite changes

plucky inlet
woeful leaf
#

Ah okay, nice

#

Sorry for not answering I was kinda looking up how switch cases work for switching types again heh

plucky inlet
#

yeah, you cant really switch types directly ๐Ÿ˜„ I think someone here had that conversation yesterday too ๐Ÿ˜„

woeful leaf
#

Yeah exactly, since the value has to be a constant in switch cases, so I needed to look up how you can do it heh

#

Switch cases are great but they can also be limiting in some areas

plucky inlet
#

I would have been fine with a simple if T is myClass, but thats not working either in my generic usecase. But yeah, not really useful to work more on that as it is a project that will be fixed to this dataset anyway ๐Ÿ˜„

woeful leaf
#

Yeah no need to spend a lot of time making it dynamic if it'll never change anyway

#

Though that being said, if you ever just don't have anything to do, you can just (try to) make it dynamic for experience :P

#

I find experimenting one of the most fun things in programming

plucky inlet
woeful leaf
#

Haha, that's understandable :p

woeful leaf
plucky inlet
plucky inlet
woeful leaf
#

Just the recttransform, I want the "bounding box" to be bigger so the IDragHandler effects a larger area

#

It's quite funny because now I use IDragHandler instead of IPointerEvent, which now I just have a different issue, I'm just trading a problem for another problem heh

plucky inlet
#

-20 is like random ๐Ÿ˜„

woeful leaf
#

Like it should be simple to do in code, but for some reason it just doesn't recognize it's supposed to resize from the center

#

Whilst when you do it manually in the inspector it does

plucky inlet
#

Or rather, from where is it scaling if you say, its not from the center?

woeful leaf
#
box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
text.rectTransform.sizeDelta = new Vector2(text.rectTransform.sizeDelta.x, 40.22f);
box.size = new Vector2(text.rectTransform.sizeDelta.x + 40.22f, 40.22f * 2f);

Well that's how I do it through the code, and sizeDelta is the same as the width and the height

#

So I adjust the width and the height in the inspector and that does center it from the middle

#

I do see now that the alignment is bottom corner again now though which is weird

#

Okay now both don't scale from the center whilst yesterday it did ;-;

thin aurora
plucky inlet
woeful leaf
#

Hm lemme see

woeful leaf
#

Ty

woeful leaf
#

Well I mean it does, but still not from the center

plucky inlet
woeful leaf
#
box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
text.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 40.22f * 2);
woeful leaf
plucky inlet
plucky inlet
woeful leaf
#

The bounding box should be on the center point of the text, so that it's the same above and below

plucky inlet
woeful leaf
plucky inlet
woeful leaf
#

Oh my god I'm stupid lmao

#

Good point, just adjust where the text is alligned to

#

I don't know how I didn't think of that

thin aurora
#

@slow crag Here is a very broad example on how to properly implement asynchronous initialization. You should probably abstract most of this since it's a lot of repeatable code. https://hastebin.com/share/oxuyujumur.csharp

woeful leaf
#

I suppose I was still just confused by using the box collider which is set and centered differently than the rectransform

thin aurora
#

Notice how this actually properly handles any exceptions that might happen

woeful leaf
#

So I didn't think of the solution of just centering the text within the field

#

Now just to figure out how I center it in code

plucky inlet
woeful leaf
# woeful leaf

Basically pressing the second button but in code which centers the text in the middle of the bounding box :p

#

I just need to look up what the syntax is for it

plucky inlet
woeful leaf
#

And it also doesn't use a prefab so I need to know how to set it in code lel

plucky inlet
woeful leaf
#

Probably, but at this point I'd have to rewrite the code then for it heh

woeful leaf
plucky inlet
woeful leaf
#

Fair enough hah

#

I'm still studying so I've not gotten all too much experience with Unity just yet

#

I've like 1.5 years of Unity and 2 years of C# I think

#

(My math is crap so if the numbers aren't right I blame it on that heh)

plucky inlet
# woeful leaf I've like 1.5 years of Unity and 2 years of C# I *think*

it depends on your learning resources too. Back then when Unity came out, you had to figure out everything yourself ๐Ÿ˜„ that helped a lot and still does to some parts of Unity where they just dont find time to write docs ๐Ÿ˜„ So you only had little amount of tutorials if at all, but today, its the way around, you just have too much resources on too many versions ๐Ÿ˜„ But enough off topic from me ๐Ÿ˜‰

woeful leaf
#

And it's just more fun designing your own things :p

woeful leaf
chrome pewter
#

Is there any way, I can check if my unitywebrequest code works without using an API to get data from

slow crag
#

that's the exact thing I'm trying to avoid

#

keep Update as clean as possible

thin aurora
#

It's checking a boolean every frame

#

There is literally no change performance wise

slow crag
#

It's still unnecessary

thin aurora
#

Not really

chrome pewter
#

Its just good habits to keep it clean

thin aurora
#

Again, not really

#

You're going to get a heart attack if you look at what Unity does in a single frame, if you think this is bad

#

This aint 2005, c# can check a boolean each frame

#

Point is, this is a quick and efficient way to ensure your code is initialized asynchronously, whilst also handling any errors

#

Don't use it if you don't want to ๐Ÿ™ƒ

chrome pewter
#

True

thin aurora
#

The only concern you should have is heavy computing, recurring bigger tasks, or blocking tasks in general, on a main thread.

plucky inlet
#

I agree with Sampai and Caleidon, keeping it clean is good as well as avoiding update if its unnecessary. Just getting a habit of when to use what can have impacts when you are in a bigger scope later.

slow crag
#

I completely understand what you're saying and why, this is just a thing of opinion

#

I don't like my update calling if statements every single frame if I can avoid it with 2 lines of code

thin aurora
#

Alrighty, just remember that not handling errors from an asynchronous method like you're doing currently is a bad thing

#

I'm specifically avoiding that basically

slow crag
#

That's true, but my method is designed not to have errors. If they do exist I'll catch them during development. Once the game is complete, it can either work 100% or not run at all, and if the latter is the case then that's on me

#

But either way, thank you for showing me an alternate way

#

I'll keep it in mind, might come useful later

thin aurora
#

Yet they still happen

nimble dome
thin aurora
#

Thinking your methods are perfect and will never give you any errors is a very very bad way of programming, especially with a fire and forget method you just introduced @slow crag

#

I strongly suggest you add some way to ensure it works. Atleast add a try-catch block into it

slow crag
#

but this is resource loading

#

sure, a basic try catch might suffice

#

either the game loads the resources or it's like "fuck off I can't start"

thin aurora
#

But alrighty

sleek bough
nimble dome
#

    [SerializeField] private ItemData newItem; // Needs to be one of the values from itemData.

    private List<ItemData> itemData = ItemManager.instance.GetItemData;

    private void Awake()
    {
        itemManager = ItemManager.instance;
    }```
sleek bough
#

OnValidate triggers on value change.

plucky inlet
#

So if its just for the displaying of it, look into custom editor scripting

nimble dome
#

okay I assumed it might come to that. Ill see if i can find anything. thanks

#

Is it possible to make ExecuteInEditMode only update when a value in the inspector has been altered? rather than whenever something in the scene is changed?

plucky inlet
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.")
    }
}
nimble dome
#

haha my bad

#

Also, I cant seem to find it, but does OnValidate only update when the scripts object is updated? Or are all scripts with this function called?

woeful leaf
nimble dome
#

when any update happens in the inspector.

woeful leaf
#

The function gets called

#

This works for inside of playmode and outside of playmode iirc

nimble dome
#

okay thanks

#

I have decided after remembering that scriptable objects exists that it is a much better option than defining objects in another script through the inspector.

#

thanks for all your help though!

potent glade
#

why didnt it work

woeful leaf
#

Because you didn't to it properly

#

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

potent glade
#

OOOOOOH THANKS!

wet furnace
#

pls help me i want code where simulation is space moving object when click move forward go forward infinite and when rotate object and click move forward reduce speed and than go forward

plucky inlet
covert pulsar
#

hello. I need to know how to find out memory usage in while the user play, but not in profiler, but via script

plucky inlet
covert pulsar
#

Alright, but I just crossed post because someone tell me to ask me on another channel

wet furnace
#

what can i do? they didnt help me

plucky inlet
#

Try to give as many detail about your problem as well as the code you have tried

thin aurora
trim schooner
rustic ember
#

How can I get the forward velocity of a Rigidbody?

terse venture
#

Hello

public class RotateBlue : MonoBehaviour
{
    public GameObject Anchor;
    public float speed;
    public Vector3 Axis = new Vector3(0, 0, 1);

    public bool onTile = false;
    public bool hasclicked = false;

    public Vector3 TileLocation;

    public RotateRed red;

    public bool isActive = false;

    public bool hasswapped = false;

    // Start is called before the first frame update
    void Start()
    {
        onTile = false;
        hasclicked = false;
        isActive = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (onTile == true && isActive == true && hasswapped == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                hasswapped = true;
                Swap();
            }
        }

        if (isActive == true && hasclicked == false)
        {
            transform.RotateAround(Anchor.transform.localPosition, Axis, Time.deltaTime * speed);
        }

        if (hasswapped == false)
        {
            hasclicked = false;
        }
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("tile"))
        {
            onTile = true;

            TileLocation = collision.transform.localPosition;
            TileLocation.z = -1;
        }
    }
    public void OnTriggerExit2D(Collider2D collision)
    {
        onTile = false;

        //collision.gameObject.tag = "Untagged";
    }

    public void Swap()
    {
        hasclicked = true; //stops from moving
        isActive = false;
        this.transform.position = TileLocation;

        //move oposite colour
        red.isActive = true;

        red.hasswapped = false;
    }
}

My script is running fine, but the blue version of it is the same.

#

When they swap it straight away swaps back as it satisfies the conditions for some reason

#

how would i fix this

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.")
    }
}
terse venture
#

all it needs to do is swap over player, and its swapping over, except i cant click to swap as it straight away swaps back and displays like nothing hapopened

swift falcon
#

hi, do i have to learn c# first or just go for unity?

terse venture
terse venture
thin aurora
#

Wow what a bad example

#
yes it does value int void
terse venture
#

just removed hasswapped bool as that was just to test, isActive will be the main one

woeful leaf
terse venture
#

it all works, ahh
It runs this code, but then it displays as it doesnt, as the other script makes these variables true/false

woeful leaf
#

The this is unnecessary btw

terse venture
woeful leaf
#

Well you don't need to, it's just redundant

terse venture
# terse venture it all works, ahh It runs this code, but then it displays as it doesnt, as the o...

just realised. this.transform.position = TileLocation; runs. Nothing else runs!! but then it could be running, and it could just be switching back to true/false from the other script, but the other script shouldnt be running this since it shouldnt and doesnt detect the click since its deactive, unless because theres no delay, it is detecting the click in the split second when it comes back as true... ahh

#

cause it only does the click if its active, which until the code in Swap(); runs in the oposite script, it shouldnt be active, and isnt active

#

id send a video to help explain, but no discord nitro

jagged laurel
#

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

jagged laurel
#

!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.")
    }
}
terse venture
#

video showing what i mean

woeful leaf
#

mp4 would be nicer so it actually embeds

terse venture
terse venture
#

done, i spam to run the method alot

#

you can see it working, but the boolean values aint changing. I assume the oposite script is just changing it right back @woeful leaf

woeful leaf
#

What exactly is the intended behaviour and what is it doing that is not the intended behaviour

terse venture
#

but i assume when it does this, it straight away runs this on the other script, which changes it straight back

woeful leaf
#

You don't need == true btw

terse venture
woeful leaf
#

I mean fair Ig

#

Normally it's just used without it, and if you want to check for false you use !

woeful leaf
#

Where is the code for the red ball

terse venture
terse venture
#

just debug logged it

woeful leaf
#

You have the same script on both objects or?

terse venture
#

just these type of things switched

plucky inlet
#

first, that ๐Ÿ˜„ and cany ou show your full script

woeful leaf
#

You should look into inheritance or just use a main script that controls both

woeful leaf
#

In a pastebin probably

terse venture
plucky inlet
#

Also you can just use public values on your different balls if needed to set the colors you want...

#

show your full script please

woeful leaf
#

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

terse venture
#

both are there

woeful leaf
#

This is probably not needed unless you do some very funky stuff that you shouldn't be doing in the first place

#

But yeah the problem lies in that you call both functions because they don't really know anything of eachother

#

It's poorly designed code

terse venture
woeful leaf
#

So why'd you have to do it again in Start

terse venture
woeful leaf
#

You even set them to false explicitly as well

#

So it's like double overkill lol

terse venture
woeful leaf
#

I think using a main controller script would be better in this case

plucky inlet
#

What was the issue again? sorry, cant find teh original post ๐Ÿ˜„

woeful leaf
#

You could use inheritance but I don't think that's the best option here

woeful leaf
terse venture
plucky inlet
#

But they are not related to each other, are they?

woeful leaf
terse venture
plucky inlet
#

Oh wait, they are? you referenced them, okay, now I got your code

woeful leaf
plucky inlet
#

What do want them to do?

woeful leaf
#

Or red on default, it doesn't matter

plucky inlet
#

Like if one swaps, the other swaps too?

woeful leaf
woeful leaf
terse venture
# plucky inlet Like if one swaps, the other swaps too?

nah, if red clicks on a tile, it swaps. It should then do the same with the blue, but it straight away swaps since it thinks you clicked on it as the swap over happens in a split second meaning the click is active on the blue and runs swap..

terse venture
plucky inlet
#

is the game design going to only have two of those circles?

woeful leaf
#

If not then that's a whole other can of worms

#

Then it should just be a bool swapping state

terse venture
woeful leaf
#

It should not be the hardest to implement

terse venture
#

but thats kinda what ive done

woeful leaf
#

But you went a very weird way with it

plucky inlet
#

so you could just make a static bool which is redActive for example. so you know, what is currently the state

terse venture
#

ive done isActive on both

#

and change whether it is active or not

plucky inlet
#

BUT you have to use the same script if static boolean being used

#

or a main controller, yeah.

woeful leaf
#

I think the latter would be the best

#

I don't see much use in having it the way he has now

#

And if he does want it that way he does have to use inheritence

plucky inlet
#

Why? Blue and red are doing the same thing, just opposite

terse venture
#

so you would say remove the active, and the swap function to be in a main controller script that changes the active seperately..

woeful leaf
#

Else it's just dupe code ish

woeful leaf
#

Yeah you've like one script that's just on an empty gameobject that has a reference to the red and blue ball and controls it from there

#

At least I think that'd be a good approach

terse venture
#

yep ill try that now!

plucky inlet
terse venture
#

shouldnt be too hard to fix it

woeful leaf
#

And just more inconvenient because he'd have to change both scripts if he wants to add something because he also doesn't use inheritance

#

Which in turn gives more dupe code

plucky inlet
woeful leaf
#

Ah yeah I suppose you could just use one script but still slap it on both

plucky inlet
#

But I agree, just add one more ball/circle, and that approach is gone ๐Ÿ˜„

woeful leaf
#

Though I still feel like that'd become a problem at some point because you don't know which object you're using and else you've to define only do A if it is object B on a script that is on both object A and B

terse venture
#

something like this?

woeful leaf
#

And it'll also be quite a lot more to manage

plucky inlet
#

thats what swapping "should" be doing

woeful leaf
#

It inverses the bools

terse venture
#

oh

#

Ohh

#

thats cool

shut bear
#

Hey all, I have a question. If i have the red X as a position, how do i get the green X thats always the opposite side of the middle?

woeful leaf
#

Math

plucky inlet
woeful leaf
terse venture
#

WORKS

#

TY SO MUCH GUYS

woeful leaf
#

Out of curiosity, what's the code now?

terse venture
#

ill send a video of what it was actually meant to be like lol

woeful leaf
#

(As mp4 please)

terse venture
#

probs terrible way of doing it, but its a way

plucky inlet
boreal mango
terse venture
vestal crest
#

if i add #if unity_editor at the start of the method and #endif at the end of the method, that means they will not be added to build right?

woeful leaf
#

blueactive should be blueActive btw, code conventions

woeful leaf
#

Though the syntax is wrong, it should be in all caps

vestal crest
#

yea its all caps

#

i have a customeditor script

terse venture
vestal crest
#

thats why i asked i added if to method i call from it

#

thanks

terse venture
#

its terrible rn

#

but it works

#

the hit detection needs to be redone

#

plus i need to readd my code that means you cant go back a tile (just gonna untag the tile you exit as Untagged)

woeful leaf
#

Can't you just activate the other in the Swap

terse venture
#

LOL

#

im such an idiot

woeful leaf
#

Have you done tutorials and stuff for C#/Unity? Stuff like Unity Learn !learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

terse venture
#

i have indeed. Just my mind today

woeful leaf
#

So what's your code now?

#

(Full code)

terse venture
woeful leaf
#

Wait why do you still need a seperate script on the balls

terse venture
#

im still getting it sometimes where it switches straight back

#

ahhh

woeful leaf
#

Yeah because you still have scripts everywhere apparently

terse venture
#

i got 3 scripts

woeful leaf
#

Show all the code that is in use for this action

#

Why?

terse venture
#

main controller

woeful leaf
#

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

woeful leaf
#

Use that one

#

It allows for multiple scripts

terse venture
#

oh already did it

#

scripts are one after another

terse venture
woeful leaf
#

By the way, why is everything public

terse venture
terse venture
#

i know.. idk why i did that

#

i wrote this up when i was tired last night, then came back to it this morning and was like ahh what have i done, and rewrote half of it lol

#

and just left them ig

woeful leaf
terse venture
#

yep

woeful leaf
#

Word of advise, don't write code when you're sleep deprived heh

terse venture
#

yep

thin aurora
#

General rule: avoid public field like the plague, even when tired ๐Ÿ™ƒ

terse venture
#

lol that would be a good rule..

woeful leaf
#

Default everything to private if you end up needing it in another script you can always change it to public, if you only need it in the inspector, use [SerializeField] private

terse venture
#

now how would i fix this main issue

woeful leaf
#

By yeeting a lot of code

terse venture
#

alrighty

woeful leaf
# terse venture alrighty

I think a decent way to do it is have a script that delegates the OnTriggerEnter/Exits to the main controller script

#

For the rest you shouldn't need other code on the ball specifically

#

It's kind of hard for me to give a solution without completely writing it myself

woeful leaf
woeful leaf
# terse venture ok

And you should be able to use the same script for invoking those events, since one always stays still on a tile thus won't have OnEnter/Exit calls

vestal crest
#

hi, i instantiate prefab first and override it top prefab

#

if i call the method again i destroyimmediate them but they dont beacause they are overriden

#

i thought this would work but didnt happen

#
        {
            PrefabUtility.RevertAddedGameObject(missionElement.gameObject, InteractionMode.AutomatedAction);
            DestroyImmediate(missionElement.gameObject, true);
        }```
#

any idea how to revert override of nested prefab

woeful leaf
#
public class TriggerDelegation : MonoBehaviour
{
    public static Action<bool> OnTrigger;
    private const string tile = nameof(tile);

    private void Trigger(Collider2D collision, bool trigger)
    {
        if (!collision.gameObject.CompareTag(tile)) return;

        OnTrigger?.Invoke(trigger);
    }

    private void OnTriggerEnter2D(Collider2D collision) => Trigger(collision, true);
    private void OnTriggerExit2D(Collider2D collision) => Trigger(collision, false);
}
#

@terse venture probably something like that

#

The naming is a bit questionable in some parts but you can rename things yourself

terse venture
#

thanks for the help!

woeful leaf
#

And in your controller class you'd subscribe your function to OnTrigger

terse venture
#

ill have a go at remaking this system

terse venture
#

the rest i understand

#

oh i see

woeful leaf
# terse venture what does OnTrigger?.Invoke(trigger); do?
public class SwapController : MonoBehaviour
{
    private void TileCheck(bool trigger)
    {
        if (!trigger) return; //Only continue with the function if a tile has been entered, not exited.

        //Set the position of the coherent ball to the tile here
    }

    private void OnEnable()
    {
        TriggerDelegation.OnTrigger += TileCheck;
    }

    private void OnDisable()
    {
        TriggerDelegation.OnTrigger -= TileCheck;
    }
}
#

Whenever a ball enters or exits a tile, tagged with tile, it will run TileCheck

woeful leaf
#

That might be a good video to understand events a bit more

terse venture
woeful leaf
terse venture
#

yeah no problem! Thanks again

woeful leaf
#

But the TL;DR is that your basically have to rework the entire system, right now it's just unstable with how many random and redundant things there are, making it very hard to debug

#

And just have 1 main controller script (On an empty game object, make sure there's only 1 of it) and 1 delegation script for the OnTriggers (Which'll be on both balls)

#

Else you could go for Inheritance, but I think a main controller would be better

rotund burrow
#

I'm making a movement based game where i set the rigid body velocity every frame (fixed update). i only need rigid body for collision detection (so that i dont go through walls). I would like to get rid of rigid bodies completely if possible, including collision detection in my velocity script. is that a good idea?

woeful leaf
#

You cannot have collision calls without a Rigidbody

#

And if you directly use the transform, collision calls can be buggy

languid hound
#

How would one get the input for the right joystick? I'm not switching to the new input system it literally snaps to directions instead of being free and nobody knew why. Its really tedious too

rain minnow
rotund burrow
#

modifying the transform position

woeful leaf
woeful leaf
#

Intensifies

rain minnow
woeful leaf
#

If it's a simple game AABB collision will get you relatively far

leaden ice
woeful leaf
#

But that'd still be a pain to set up

languid hound
#

Thanks my bad

rotund burrow
#

yes that's what i'm asking about. game's physics are arcade style and not realistic

thin aurora
woeful leaf
#

I'd advise against writing your own physics for everything

#

Unless you've a lot of time on your hands and want to die due to math that is

woeful leaf
rotund burrow
#

again i dont need it realistic. for one of the abilities i'm using a collider that's just raycasts in for cycle. (unity physics collider didnt work quite well)\

woeful leaf
#

So what's the problem

leaden ice
rotund burrow
#

cause it has a lot of stuff i dont need

#

i only need collision detection

rain minnow
woeful leaf
leaden ice
#

seems like you're using quite a lot of it

woeful leaf
#

^

#

Either you use the RB or you write your own physics

#

If you like torture, go with the latter

rotund burrow
#

okay i got you

tawny jewel
#

hey, so maybe im looking in wrong places but i honestly cant find a proper solution, so basically i have a bird gameobject, and a wing gameobject as its child. i basically just want for wing animation to play when i press space and for the bird animation to play when the bool is set to true. i have a seperate script with settriggers etc. so basically now what do i put where, because putting animator and animatorscript components to both of them separately simply breaks the whole bird

#

i would really apprecieate any tips

tawny jewel
#

alright i will, thanks

frosty berry
woeful leaf
#

Yeah that's what I meant but it's been a while since I encountered the problem since I don't combine the two so just to be safe I called it "buggy"

#

It not working is still buggy ;)

frosty berry
#

yes yes

terse venture
#

@woeful leaf I found your way a little complicated, but when messing around with my previous script i somehow got it working!!

woeful leaf
#

Yeah events are a doozy to wrap your head around, but they're very useful

#

How did you fix it? ๐Ÿ‘€

terse venture
#

i made it so if the ball isnt moving its counted as its no longer on the tile (even if its sitting on the tile). This means its only checking for whether its active (for movement), and im moving it via the main controller script

#

Im now encountering a problem with my game. I know a fix, but im not sure how id code it

woeful leaf
#

What is the problem?

terse venture
#

on these corners, it overlaps the 2nd tile infront, meaning you can jump 2 ahead

#

So my thought was getting all of the tiles in an array, and every time you jump a tile, it gets the next tile in the array and changes the tag to tile

woeful leaf
#

Keep an index of every tile, if the index is 2 ahead instead of one, don't allow it to snap to it

terse venture
#

but

#

how do i get the tiles in an array. Ive only had to use GetComponentsInChildren, and done it like that, but im not getting a component

#

you cant do getchildren

terse venture
#

i havent put them into an empty gameobject yet

woeful leaf
#

Yeah you need a parent with a script on it

leaden ice
terse venture
#

so ive now got all of the tiles under a parent gameobject

leaden ice
# terse venture

GetComponentsInChildren is not going to give you them in any particular order

terse venture
#

so i could take the transforms and get the gameobject and tag them with tile, but now i gotta do that 1 by 1 and not in a foreach loop right

leaden ice
#

not sure why would want to not use a loop

rustic ember
#

How would I rotate it by x degrees around the x-axis?

terse venture
leaden ice
leaden ice
vestal crest
#

i have a context menu method, which do fill a list by parent. but when i call it via context menu prefab doesnt get overriden, so i have to create a gameobject then override the prefab, is there anyway to save it without creating gameobject

rustic ember
leaden ice
terse venture
rustic ember
leaden ice
#

think of it like adding rotations

rustic ember
#

That's so cool

leaden ice
#

so here we start with the object's current rotation and "compose" the additional x axis rotation afterwards

rustic ember
#
localVel = (transform.forward * Vector3.Dot(transform.forward, rb.velocity));```
I have this vector for forward/backward velocity. I can use the magnitude to figure out the speed, but how can I know if I am moving forward or backwards?
terse venture
#

how would i make it so when i press a key it would go through the array setting the tag for each gameobject

rustic ember
leaden ice
leaden ice
leaden ice
# rustic ember Interesting

dot product would also work yes, the dot product would be positive for locally forward velocities and negative for backwards

#

so actually our two techniques I believe will give the same Vector3

leaden ice
#

so you could also check the sign of the z value of your localVel in your example

#

and that would work too

rustic ember
#

So the z component is the "speed"?

leaden ice
#

no

#

z component is the z component of the velocity in local space

#

it's the speed on the local z axis only

#

ignoring x and y

rustic ember
#

Why do I want to use the z?

leaden ice
#

because the Z axis is the "forward/backward" axis

#

whereas y is up/down and x is left/right

#

and you wanted to know if you were going forward or backward

rustic ember
#

So the forward/backward speed is the z value?

leaden ice
#

yes

plucky inlet
#

z is part of the direction of your vector, speed would be the length of your vector in that direction if you will. Not sure if this clears things up or not ๐Ÿ˜„

terse venture
vast matrix
#

Any idea why web request downloadProgress would remain at 0? It jumps to 100 when it's done. It's about 1 min to download so it's not that it's going too fast.

webRequest.downloadHandler = new DownloadHandlerFile(tempZipPath);
            webRequest.SendWebRequest();          
            while(!webRequest.isDone) {
                OnDownloadProgress?.Invoke(fileNumber, fileTotal, webRequest.downloadProgress,version);
                await Task.Delay(150);
            }
leaden ice
plucky inlet
leaden ice
#

does the response contain a content-length header?

#

You can check by doing the request in a web browser with developer tools open

#

and checking headers

vast matrix
#

That could be it, it's a chunked transfer as well so that might make content-length a bit weird to figure out

plucky inlet
#

This here should be there:

#

So you can calculate either with downloadProgress or you calculate it with bytes loaded vs that value

swift falcon
#

does anyone have a playermovement script that would be good ?

similar to clustertruck...

woeful leaf
#

Ah yes let me just write up a movement script for you

#

We don't just hand you code, you come with a problem and have tried and attempted solutions and then we'll eleborate on that

terse venture
#

this annoyingly is just making all of the tags "tile" straight away

terse venture
#

why would that be

terse venture
plucky inlet
woeful leaf
#

And every tile will be labeled with it

swift falcon
#

Is GetComponent cheaper then TryGetcomponent

I really canโ€™t profile these tiny functions

woeful leaf
#

It really shouldn't matter much if any

plucky inlet
mellow sigil
#

If the difference is so small that you can't even measure it then it doesn't really matter, does it?

swift falcon
#

Yeah thatโ€™s true

#

Alright thanks guys

terse venture
# woeful leaf And every tile will be labeled with it

im trying to do this

all of the tiles are tagged "next tile"
if the tile is the next tile
tag it "tile"

so i was gonna do this: If click and land on previouis tile
add a value to the tile array
set it to "tile" so next tile is tile

#

or you can jump 2 tiles on corners

plucky inlet
rustic ember
terse venture
rustic ember
plucky inlet
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.

plucky inlet
#

Imagine someone with mobile screen trying to read your screenshot ๐Ÿ˜‰

plucky inlet
leaden ice
# rustic ember

can you try this:

Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity);
bool isForward = localVelocity.z >= 0;
Debug.DrawRay(rb.position, rb.velocity, isForward ? Color.green : Color.red);```
#

It seems like you're trying to draw local velocity in world space which doesn't make much sense haha

vast matrix
terse venture
plucky inlet
vast matrix
#

the for loop you have above will run for every single tile in your array and set them all to "tile"

vast matrix
#

basically it breaks down to

tile[0].tag = "tile"
tile[1].tag = "tile"
etc

plucky inlet
#

you can use tile.IndexOf(this) +1 for example to get the next tile.

plucky inlet
#

not sure indexof is working with an array, but you can just use a List instead

terse venture
#

ill try this though

vast matrix
#

You'll just need to keep track of currentIndex yourself

thin aurora
#

That is going to cause an exception

plucky inlet
rustic ember
#

Thank you ๐Ÿ™

terse venture
#

the starting 2 tiles are already tagged as "tile". (i need them to be). So to fix the rest , i assume i should make the index -2 on start?

#

wait 2

vast matrix
#

try with 2 to start, try 1 if that doesn't work

#

depends if you're current tile needs to be the second square there (index 1) or the third that's a bit off screen (index 2)

terse venture
#

weird, the 3rd tile gets tagged as "tile" when you land on the 2nd tile. Which is correct. Then when you land on the third tile, it does nothing to the 4th tile ect

#

@vast matrix

plucky inlet
terse venture
#
tile.OnTile();
#
public void OnTile()
    {
        tile[currentIndex + 1].gameObject.tag = "tile";
    }
#

which does that

plucky inlet
terse venture
#
public int currentIndex = 1;
desert shard
#

and where do you update it

desert shard
#

thats not updating it

#

thats just always getting currentTile(2) every time OnTile is called

terse venture
desert shard
#

theres no assignment here

terse venture
#

Ohhhhh

#

i seee!!!!!!!

#

im such an idiot

#

thats better

desert shard
#

tile[currentIndex++] will also work

plucky inlet
desert shard
#

if you want to increment after the calculation

plucky inlet
#

or do you set it from a main manager?

terse venture
plucky inlet
#

Oh my bad, I think you have amain manager class now.

desert shard
#

++ is currentTile += 1

sudden meadow
#

Can you tell me if I have a struct called "Tile", and I make an array of Tiles, those are all data types. But if I make a list somewhere else and add them to the list as well, are they copied as a data type or a reference?? I seem to remember something about list entries being references but not sure.

terse venture
leaden ice
#

not reference

#

if they it's a class, they are copied by reference

desert shard
#

whether its placed before or after the variable dictates when it is incremented.
++currentTile will use currentTile += 1 *before the assignment, so it'll run the next tile. and increment.
currentTIle++ will do the logic on currentTile then increment by 1.

rain minnow
desert shard
#

perhaps I'm not good at explaining

sudden meadow
#

and I can't reference the structs other than unsafe code and pointers then?

terse venture
#

hm its not working ๐Ÿค”

plucky inlet
terse venture
#

testing it again rn

#

1 sec

#

it didnt tag the next one

#

i messed around with the starting number too

late lion
plucky inlet
leaden ice
sudden meadow
#

alright thanks

leaden ice
#

You could use an array index to reference one if it's in an array

terse venture
#

thanks alot guys!

#

i did get this error when it was on the last tile

plucky inlet
#

yeah, we said that ๐Ÿ˜„

terse venture
#

(since next number is out of the array) like you said

plucky inlet
#

check if currentIndex+1 is smaller than your array length

terse venture
#

do i just check whether the current index is smaller than the length

rain minnow
# terse venture

place a check to make sure the index is not out of range . . .

desert shard
#

if(currentTile >= myArray.Length) return;
//logic