#archived-code-general

1 messages · Page 130 of 1

leaden ice
#

We covered that...

dusk apex
#

I think the function is occurring once for every object - not sure why. If so, the individual would be able to avoid a loop and just keep an index and reset on triggering of the rename command. @leaden ice

leaden ice
#

Hence the "removing numerical characters"

leaden ice
cursive moth
#

I don't have a say in that

#

as I said, it's an editor script which occurs when you select an option from the right click menu :/

leaden ice
#

Combine that with using the sibling index or a loop or whatever

honest edge
#

that doesn't really sound like unity issue to me honestly

cursive moth
dusk apex
cursive moth
dusk apex
#

It really is just a simple copy of original string name plus for loop concatenating index.

leaden ice
#

Or:

string plain = RemoveNumbers(obj.name);
obj.name = $"{plain} {obj.transform.blingIndex}";```
cursive moth
dusk apex
#

Whatever the case is, I'm not writing code. The others have got this.

leaden ice
#

You'll probably want it to remove trailing whitespace too

cursive moth
leaden ice
#

That's what removing the numbers is for

#

They get removed lol

cursive moth
#

and that's exactly what I am saying, I don't want them removed

leaden ice
#

Apple 132 becomes Apple becomes Apple1

cursive moth
#

if I have a Plant Type 12 I don't want it to become Plant Type 1 but Plant Type 12 1

honest edge
#

the only way to do that is to keep track of those "base name" somewhere, which sounds like a lot of work for not much advantage

leaden ice
#

There's simply not enough information

cursive moth
honest edge
#

If I can suggest something

cursive moth
#

thanks

leaden ice
#

Having the user input a name

honest edge
#

rename you base object like so : Plant_Type_12

cursive moth
honest edge
#

then you can parse this to inlcude the numbers as well, and use the spaces to rename stuff

#

Then you can't do it.

#

unless you control that same behavior

cursive moth
honest edge
#

if you have control over the what the user will name it, then you can do it, otherwise, not

tropic quartz
wide path
#

Heya, I'm trying to set up my game for Steam Deck. I currently have a script with this line in the Start() function:

Time.fixedDeltaTime = Screen.currentResolution.refreshRate;

Which is supposed to set the Phyics TimeStep to match the current monitor's refresh rate. This works great on PC, but not on my Steam Deck. It seems to set the value to 60 despite my Deck being set to 40Hz, and this results in some nasty juddering with physics movement. Does anyone know why that is happening, or how I can get a more accurate reading, or what else I can do to fix this?

cursive moth
tropic quartz
honest edge
wide path
#

I agree a steam deck channel would be nice. But I am specifically trying to figure out what code to write to achieve a specific outcome, so I figured here would be best

mossy snow
molten thicket
#

That's quite strange @wide path

I would only assume it would be a limitation / configuration thing on the deck itself

#

Because if the code works, it should work on the deck as well.

The software wouldn't vary THAT much... right?

wide path
wide path
#

Or maybe it's a compatibility thing since Deck is linux

mossy snow
wide path
mossy snow
#

that would still be wrong

#

1 / 60 = 0

#

1f?

wide path
#

Er, yeah

buoyant crane
#

a bit weird tbh UnityChanThink

wide path
#

So physics movement will look perfectly smooth. Using interpolation doesn't work in my case

pale spindle
#

Can someone let me borrow their Fade In/Out scene changer?

#

i am in need of something and i am pulling up 054303053405630530530560305345052340123042304230452045E+30 tutorials on yt

#

and so far 7 of them are trash im told

wide path
#

And so the mismatch is causing a judder

buoyant crane
pale spindle
#

anyone?

buoyant crane
#

Whoever did, probably has a script 🤔

pale spindle
wide path
pale spindle
#

this is not valid in 2023

buoyant crane
honest edge
#

Isn't the idea to just have a black rectangle to show in front of your camera while you do stuff in the background, and whenever ready, just switch it or fade it with transparency. That should be pretty easy to adapt from these other tutorial, no?

pale spindle
#

so what tutorial you recommend?

#

or can i steal someones via asset store

#

since thats all most people do now lol

wind palm
pale spindle
wind palm
cursive moth
#

Hi, I made this script for mass renaming things and there are 2 issues(one of which I kinda solved):
First one being that it opens as many dialogs as there are selected objects(fixed with a bool that checks if it's currently open but seems like a messy workaround)
Second being that when I change the value of the input it doesn't really change.
It shows the new name as long as the input field is selected but as soon as I de-select it/press the Rename button it turns back into it's original text and my items are renamed to that instead of the new input name.
Any thoughts as to why this is happening?
https://gdl.space/rokimiyeke.cs

buoyant crane
cursive moth
pale spindle
iron nymph
#

Is there a way to get voicedata in facepunch.steamworks

#

because from what I've seen there is literally no way to do this even though there are ways to read voicedata in it

cursive moth
cursive moth
dusk apex
#

Bulk rename @cursive moth

using UnityEngine;
using UnityEditor;
using System;
public class Sample : MonoBehaviour
{
    [MenuItem("GameObject/Rename")]
    private static void Rename()
    {
        Debug.Log("Renaming...");
        var arr = Selection.gameObjects;
        if (arr.Length < 1)
            return;
        Array.Sort(arr, (a, b) => String.Compare(a.name, b.name));
        string str = arr[0].name;
        for (int i = 0; i < arr.Length; ++i)
            arr[i].name = $"{str} {i + 1}";
    }
}```
cursive moth
dusk apex
#

Uncertain but the normal behavior is that of a single instance.
The data is unsorted though, thus the need to sort.

cursive moth
#

I see, I made the new approach(which I consider better because it's easier to use) but I can't figure out how to detect the window close.
It works fine till you use the x button that comes with the EditorWindow

lean sail
#

since its relying on sorting the strings

dusk apex
cursive moth
lean sail
#

I would probably do this differently, regex to get the name excluding an ending number then run the for loop from there

dusk apex
#

Yeah, that was what blue suggested.

#

Where copies would be grouped together.

lean sail
dusk apex
#

GameObject N, GameObject (N) and GameObject (Clone) are pretty common so you may want to consider parsing for those as well.

cursive moth
#

the approach I just provided doesn't rely on any previous names :/

lean sail
#

sorting strings is weird because of the case of a string being shorter than another. Also it may not be obvious but the numbers in the string dont get sorted as numbers

#

so you end up with weird orderings sometimes

lean sail
dusk apex
#

Well, ideally you'd get the lesser in value including number of characters and value of character.

cursive moth
dusk apex
#

These are all editor stuff and should not really be discussed in this channel.

cursive moth
wide path
vagrant cradle
#

is there a way to detect a collision between VoicelineTrig1 and something with the tag of Player, even if the script isnt attached to the parent object of VoicelineTrig1?

here is what i have so far.

    //...

    private BoxCollider2D VoicelineTrig1;
    // Start is called before the first frame update
    void Start()
    {
        VoicelineTrig1 = GameObject.Find("VoicelineDetection1").GetComponent<BoxCollider2D>();

        //...
steady moat
# vagrant cradle is there a way to detect a collision between VoicelineTrig1 and something with t...

Watch this video in context on Unity's learning pages here -
http://unity3d.com/learn/tutorials/modules/beginner/physics/colliders

What Colliders do, and how to setup different collision geometry with primitive, compound and mesh colliders.

Help us caption & translate this video!

http://amara.org/v/V6cI/

▶ Play video
oak plover
#

got a question. have a movement script and suddenly it wont let me jump and idk what i did wrong lmao https://hatebin.com/hemzebobsw thats the code. i feel stupid rn ngl

vagrant cradle
honest edge
#

is you comment these both, does the issue remain?

#

I have a feeling this is coming from this so I'd debug by removing this part of the code first, test again and try to pinpoint where the issue is coming from.

oak plover
#

ok so i removed the one in the fixed update and it still happens and if i remove the one in the void update it does not work\

#

thats the fixed update one removed

honest edge
#

I mean. comment both of them, and just assign "false" by default to your variable. That way it should go straight to the part you want to jump test

#

wait. I'm looking at it more. IsGrounded is just to know if you touch the ground or does it mean you "CAN'T" jump?

#

cause you have unreachable code here.

oak plover
#

ok so

#

isGrounded i belive is to see if im on the ground and if i am on the ground i wanna jump. i also made it so when i jump the longer i hold space the higher i go to a max limit i can set

honest edge
#

red is false, green is true

#

When you're in "else", isGrouded is always false

oak plover
#

wait so how would i fix this?

honest edge
#

is taht coming from a tutorial or something?

oak plover
#

no someone was teaching me and i got to isGrounded point and i decied to try to make it so when i hold space i jump higher lol

#

after I did this jumping wouldnt work and i couldt figure how to fix it

honest edge
#

yeah logic is just wrong to do that

#

hmmm. one sec. let me check more

oak plover
#

ok take your time blushie

honest edge
#

I don't think you need the first if

#

if (IsGrounded)

oak plover
#

ok uno sec

#

wait so

#
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
#

that one?

honest edge
#

no. that's alrgith

#

I meant the condition

#

you already have a bunch of conditional "movement" stuff in the else part. that's proabably all you want. I can't write the code for you, but I'd start there for sure

#

You're already executing them in conditional statement based on the "State" of your actor

oak plover
#

uh ok thank you ❤️

honest edge
#

just expand a litle more and ensure they don't overlap

oak plover
#

ok

#

oh

#

ok

#

so

honest edge
#

first thing I would do is list all "State" you want to have. I mean
move
move + jump
jump + jump
etc

oak plover
#

its fixed but ill have to sort out the fact that it just flys when i hold space infinitly

honest edge
#

and then see what "State" you'll need in condition to do all of that

oak plover
#

lol

#

ok

honest edge
#

yeah, that's what I meant by "overlap"

oak plover
#

i wish there were vc's tbh lmao it'd be so much easier to explain stuff to peeps

oak plover
honest edge
#

list your states. then use conditional to check if the current "State" is alrgith for you to hit the space bar or not

oak plover
#

i got it so i made a float earlier

honest edge
#

if (Input.GetKey(KeyCode.Space) && isJumping && !IsGrounded && !DoubleJumping)

oak plover
#

i adusted it so it works

#

now i just need to make it fall faster over time and im set

#

lol

#

thank you for your help nmy guy

honest edge
#

no problem. hope you can figure out the rest. If not, just come back here

oak plover
#

ok thx

oak plover
#

@honest edge do you mind if i add you so i dont gotta msg in this chat, i may or may not need some help again lmaoo

honest edge
oak plover
#

ah kk got it

graceful flume
#

Can i ask why this code need a vector3 variable to store the mouse position ? For my understanding the mouse only move in 2 dimension only so why do we need the z axis ?

potent sleet
#

it will just 0 out the z

graceful flume
#

even if i'm working with 3d game right ?

potent sleet
#

yes screen space is 2D

graceful flume
#

or i have to use vector3 if my game is in 3d

potent sleet
#

depends what ur doing

buoyant crane
#

same thing goes for Vector3

graceful flume
fading trail
#

hey sorry. I've been trying to understand marching cubes algorithm for a bit and if anyone could explain it simpler or send me any material that would be much appreciated. I already watched sebastian lague's video and im still kinda confused about it. If anyone wants to talk about it or is confused as well we could talk about it just to try to understand it

deft cape
#

someone please explain why setting the variable here works for mouse sensitivity, and move speed, but not for interactdistance [It is not set nor changed anywhere else]

#

[the x rotation is changed because I moved my mouse in game]

wide path
sour matrix
#

I'm trying to debug strange behavior with my code relating to the Character Controller. Specifically:

  1. Sometimes I am able to jump multiple times midair
  2. Sometimes I cannot jump at all
  3. Sometimes I move much slower than normal
    Attached is my very simple player script. I assume this is the source of the problem, but I'm not sure how or where.
    https://hatebin.com/mdukiqfeqq
#

Additionally, here are the settings for my character controller

warm forum
#

Can someone please make the script for 4 heroes to battle any number of monsters?

sour matrix
warm forum
sour matrix
#

How much C#/Unity do you know?

#

If you're referring to my message, I have a weirdly formal writing style that comes from various places, specifically emails. I also think this is funny to do

#

If you're referring to the code, no

quartz folio
#

!mute 234441532671787009 1w you have been warned for: "Stop asking for free work. If you're not going to show your attempts, you won't be allowed to post. " and demanding scripts many times. This is your final warning, accompanied with a week-long mute. Next time you will be banned.

tawny elkBOT
#

dynoSuccess joeynigro#0 was muted.

sour matrix
#

I know more of Java than C#, and my current C# skill is basic. Most of my background is in Rust

#

What's the usual way to initialize variables, then?

#

Oh, through the inspector. I'll use that method then

deft cape
#

I just remade the variable right below it exactly the same and the issue was not present (so im just calling that specific line as cursed)

deft cape
#

literally 0 idea why it was being set to 100 lmao restarted editor n everything twice

sour matrix
#

I haven't used Unity in two years. Most of this has been trial and error and what makes visual sense to me

#

I don't know what the preferred Unity way is for doing things and I don't know where I would even find such a thing

lean sail
# sour matrix I'm trying to debug strange behavior with my code relating to the Character Cont...

you should add debugs to see why you are able to jump many times, im unsure about that one specifically but ive heard the character controller isGrounded value is kinda weird.
For not jumping at all, this may just be the same issue, but one thing i notice is

        if (_controller.isGrounded && _movementVector.y < 0)
        {
            _movementVector.y = 0;
        }

will immediately stop your jump if you are grounded and have any downwards force

#

really most of this you should add debug statements or make your _movementVector public/serialize field so you can just see its values in the inspector rather than printing it every frame

sour matrix
#

I don't know how to use samples, and when I first searched this issue online, the first thing I read said that the sample was outdated and broken

#

Again, I haven't done anything in Unity for two years

#

If there's a proper way of doing things, I'm all ears

ebon apex
#

can someone let me know why i keep getting this error when i try to build

dusk apex
ebon apex
dusk apex
rustic nymph
#

hey guys, is there a way to make the line renderer to automatically targets the enemy object when i shoot?
thinking of like no matter where the player is facing but the line still shoots at the object/nearest target
heres the code for it

lean sail
fervent furnace
#

you are setting transform .forward as the ray's position...

iron nymph
#

Is there a way to turn byte arrays into audio clips?

lean sail
rustic nymph
iron nymph
#

So I'm trying to get proximity voicechat to work in my game and one way you can get voice data is by byte. I'm currently just trying to find out how to convert the byte arrays to audio clips so you can ofc hear it

#

Another way you can get audio data is MemoryStreams but I first want to start off more simple with bytes before going to that

fervent furnace
#

for naive approach, just find a array or list to store all the GOs
for complicated approach, i have no idea

iron nymph
#

@lean sail Do you have any idea how to do this

lean sail
#

and tutorials

spring basin
#

Hello, where do I find APIs provided by Unity's Wire package?
Does anyone know if it has a API to check network connection or connection to Unity Gaming Services itself?

twin hull
rustic nymph
viral yacht
#

Anyone want to help me make a game for free?

fervent furnace
#

no

knotty sun
tawny elkBOT
viral yacht
#

It's annoying

#

Why do you care about money?

knotty sun
#

I don't see how that question is relevant to the rules of this server

swift falcon
#

is there a 3D Rigidbody version of OverlapCollider?

viral yacht
fervent furnace
#

?

viral yacht
#

You don't have to be rich

fervent furnace
#

Physics.OverlapSomething?

swift falcon
viral yacht
#

Like mater once said: "Money ain't gonna make you feel better"

swift falcon
#

2D physics api seem to be way different

fervent furnace
#

but this is a static method of physics class not collider2d

swift falcon
viral yacht
#

Exactly

#

Just like one guy started it you can do it too

swift falcon
viral yacht
#

Money isn't all about richness it's about the amount you have

#

That's all that matters

hidden parrot
#

What the hell is this guy saying?

knotty sun
#

@viral yacht you posted about collaboration, I showed you that that is not allowed here and where to post. There is also no off-topic allowed on this server which all your subsequent posts have been. Further more this is a code channel so why did you even post here in the first place?

swift falcon
#
Vector3 center = new Vector3(Screen.width / 2, Screen.height / 2, depth);

is this a reliable way to get the center of the screen? It looks right of course but im wondering if there are better ways, or is this the best way

hidden parrot
#

Believe so but does it return a screen point or a world point?

#

Oh it's pixels

hidden parrot
#

Oh god he's still trying

swift falcon
hidden parrot
swift falcon
hidden parrot
#

Ah

knotty sun
swift falcon
#

I forgot to remove that from the snippet srry, ignore it there

#

and yeah its incorrect

#

but the general idea of dividing width and height by 2

knotty sun
#

yes or *0.5f

swift falcon
#

alr

knotty sun
# swift falcon alr

width and height are ints, / 2 will also give an int so Vector2Int should be the result

swift falcon
#

Yeah thats good, thanks

knotty sun
fervent furnace
#

the compiler should compile any /2^n to >>n (except negative integer) so i think run-time is still the same

knotty sun
#

maybe, but if not there is unnecessary overflow/underflow conditions tested

#

its the asm programmer in me, I always prefer explicit bitshifts when possible

knotty sun
#

enough with the bs
<@&502884371011731486>

quartz folio
#

!warn 770034486804480110 there is no off-topic, and job posting or collab/job requests are not allowed on this server.

tawny elkBOT
#

dynoSuccess robal9874#0 has been warned.

vocal root
#

Any1 knows a good 3d grid system tutorial? On youtube are specific to 2D or the CodeMonkey ones are imposible to follow since the code he references from previous videos is heavily different between tutorials

steady moat
vocal root
steady moat
vocal root
#

Im trying to do a thing like Xcom for example

steady moat
#

I do not know what you mean by displaying.

vocal root
#

I want the grid to be seen

#

squares on the floor

steady moat
#

I'm not familiar with XCom, however Turn Base game are usually 2D grids.

fervent furnace
#

multilevel grid is just a some separate 2d grids
similar to hierarchical search

steady moat
#

To be honest, I am not totally sure what would be the best way to show a grid.

vocal root
#

Like this, maybe i was bad at words

#

But right now im using a shader, that is not very acurate

steady moat
#

It does seem pretty good doesnt ?

vocal root
#

Yeah but what i said, its a shader so Its not really useful because of size and scales

#

thats why i wanted some "real" grid

#

To snap things well and not by hand

steady moat
#

I mean, the shader is probably the best approach.

#

You just want to combine it with a code that manipulate the shader.

strong nimbus
#

Hi. I have a bouncing ball game, and I wanna restrict the angles it bounces because I am using a sphere collider and the unity and rigidbody physics system ( Ireally doint wanna have to make my own physics). So hereis what I wanna do:

I wanna lock the bounce angles to 22.5 degree increments.
I have tried using several different codes but they all faulter at one point or another, could someone either show me some example code or just tell me the logical process to making this work?

#

here is some code I already used, I used 90 degrees to visually see if it works, but for some reason the ball still bounces at "off" angles, for example if I angle the wall 22.5 degrees the ball surely doesnt bounce at a 90 degree angle as expected in the code below

heady iris
#

there's some artifacting because of the low resolution, I guess

heady iris
steady moat
#

If every corner is 90 degrees, I can see how you can manage without the normal, however in a scenario where it has other surface possible, you probably need the normal.

#

Reflection is base on the normal of the surface and the incident angle.

strong nimbus
#

I see. When you say normal do you mean normalize or?

steady moat
#

No, I mean the normal.

leaden ice
#

I would just do this in FixedUpdate and call it a day 😆

int segments = 16; // 22.5 degree angle

void FixedUpdate () {
  Vector2 vel = rb.velocity;
  float mag = vel.magnitude;
  float angle = Vector2.SignedAngle(Vector2.right, vel);
  angle /= (360f / segments); // 16 segments for 22.5 degrees. but insert your segment count here
  angle = Mathf.Round(angle); // round to the nearest segment
  angle *= (360f / segments); // scale back to 360 degrees
  Vector2 result = Quaternion.Euler(0, 0, angle) * Vector2.right * mag; // make a vector at that angle with the original magnitude
  rb.velocity = result;
}```
_note this has not been tested and I just wrote it in Discord_
steady moat
#

In 3D yu have hit.normal.

leaden ice
#

it describes the orientation of the surface

strong nimbus
strong nimbus
leaden ice
strong nimbus
steady moat
leaden ice
#

at worst it should go in the wrong direction

steady moat
leaden ice
#

I assumed some other code is giving it an initial velocity

steady moat
#

If it has no velocity prior.

strong nimbus
#

when I click space it gives velcoity to a preset value

#

Honestly I am super lost, I found this code online and just tweaked it, I am gonna check some youtube physics tutorials lol

#

Thanks guys

royal pulsar
#
public class Purchaseable : MonoBehaviour
{
    [SerializeField] private Dictionary<ItemData, int> cost;
    [SerializeField] private DynamicInventory inventory;

    private void AttemptPurchase()
    {

    }

I have this code which can be placed on a gameobject to make it purchasable. It should take in a cost and then compare the player's inventory state to the cost and if so attempt a purchase.

I attempted to define a cost by using a dictionary. This would allow me to support a cost of multiple items of different item types. However, dictionaries do not seem to be serializable in Unity. Is there a standard approach to something like this? I am not familiar with many data types in programming.

fervent furnace
#

yes, unity does not serialize dictionary

royal pulsar
#

I see

#

maybe I can make an enum Cost and use a list of Costs instead

heady iris
#

Yes, one option would be:

#
[System.Serializable]
public struct Cost {
  public Currency currency;
  public float amount;
}
#

I've done that in several contexts (item price, weapon damage...)

#

Sometimes, you do wind up wanting a dictionary. You can build it at runtime if needed.

royal pulsar
#

Cheers, I think i'll go with that

dusk apex
heady iris
#

It's only annoying in situations where you want every choice to be present automatically

latent latch
#

There's implementations for a serialized dictionary on the forums if you want to dig around, but just building it at runtime is what I do

dusk apex
heady iris
#

I've used the serialized dictionary thing from time to time, but it's a little bit fiddly

candid moon
#

https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs

Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime

Components:

Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script

Animator in the child object

private void OnTriggerEnter(Collider other)
    {
        if (other.name == "WalkToPos")
        {

            nav.ResetPath();

            animator.SetBool("isWalking", false);

            nav.updateRotation = false;
            Rigidbody rigidbody = GetComponent<Rigidbody>();

            rigidbody.velocity = Vector3.zero;
            rigidbody.constraints = RigidbodyConstraints.FreezeAll;

            StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));

        }
    }

IEnumerator CustomerSit(GameObject sitPos)
    {
        yield return new WaitForSeconds(0.4f);

        transform.position = sitPos.transform.position;

        print(transform.position + " " + sitPos.transform.position);
        print(transform.position);


        transform.localRotation = Quaternion.Euler(0, 0, 0);
        transform.rotation = Quaternion.Euler(0, 0, 0);

        Animation customerSitAnim = GetComponentInChildren<Animation>();

        animator.SetBool("isOrdering", true);

        ChooseRandomItem();

        sitting = true;
    }```

Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.

▶ Play video
swift falcon
#

so i am doing a third person movement and i've encountered a bug: when you spin on yourself too fast (clockwise or counterclockwise) the player just falls (its rotation changes even tho it should be frozen from the rigidbody component). to better understand the problem i temporarely deactivated the movement script, and found out that it's the rotation script that is causing this problem: https://gdl.space/uvozoxogoy.cs.
the script is attached to the main cam

steady moat
swift falcon
#

the problem seem to increase when i decrease rotation speed and it seems to disappear when i increase it

steady moat
#
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
viewDir.y = 0;
orientation.forward = viewDir.normalized;
swift falcon
#

thanks, let me try, i'll be right back

steady moat
#

I might not, be it is definitely what you want to do. It make no sense to look up.

jaunty needle
#

Hello guys, I'm trying to get an object to look towards the player when it gets within a certain detection radius but only on one axis

#

I don't know how to do that, I tried this jumble of code but it's just broken:

    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            //turn towards the player a bit 
            
            Vector3 objectLookDir = transform.up * -1;
            Vector3 playerLookDir = cameraTransform.forward;

            float angleBetween = Vector3.Angle(objectLookDir, playerLookDir);

            Vector3 newDirection = Vector3.RotateTowards(objectLookDir, playerLookDir, rotationSpeed * Time.deltaTime, 0f);
            transform.rotation = Quaternion.LookRotation(newDirection);


            print(angleBetween);
            yield return null;
        }
    }
swift falcon
leaden ice
# swift falcon nope, sadly doesn't work

you also have to fix this code:

            Vector3 dirToCombatLookAt = combatLookAt.position - new Vector3(transform.position.x, combatLookAt.position.y, transform.position.z);
            orientation.forward = dirToCombatLookAt.normalized;

            body.forward = dirToCombatLookAt.normalized;```
#

Though it's unclear what the difference between all these variables are:

    [SerializeField] private Transform orientation;
    [SerializeField] private Transform player;
    [SerializeField] private Transform body;```
leaden ice
jaunty needle
#

The z axis

swift falcon
jaunty needle
#

you know like a creepy turn to face the player

leaden ice
jaunty needle
leaden ice
#

Do you mean rotate only on the y axis?

jaunty needle
#

Sorry

#

Yes that is what I meant

leaden ice
# jaunty needle

the fact that that axis is the blue one means your object is already laying on its side/face

swift falcon
leaden ice
#

so I'd say the first thing to do here is fix your whole object setup

#

so that y is up

#

and z is forward

jaunty needle
#

Yes it's kinda messed up I didn't import it properly from blender

leaden ice
#

as it should be

jaunty needle
#

Ok

leaden ice
#

or you will struggle endlessly with this stuff

jaunty needle
#

Yeah I remember struggling with it in the past

jaunty needle
#

I know it has something to do with these settings

leaden ice
steady moat
steady moat
#

You might have an issue with the camera switching which mean that the code is executed anyway.

swift falcon
#

alright @steady moat thanks to the help that u provided in ur first message i managed to fix it. thanks a lot!

steady moat
#

What was the issue ?

swift falcon
#

everything remains the same besides:
if (inputDir != Vector3.zero)
{
body.forward = new Vector3(Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed).x, 0, Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed).z);
}

#

i removed the y from this

steady moat
#

I see

#

Use a variable instead of doing the calculation twice.

swift falcon
#

like this?

if (inputDir != Vector3.zero)
{
Vector3 slerp = Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
body.forward = new Vector3(slerp.x, 0, slerp.z);
}

steady moat
swift falcon
#

thanks!

#

i can now continue developing. i have some more bugs to fix, but i'll ask that later

swift falcon
#

anyone knows how to make a world system like pixel worlds or growtopia?

jaunty needle
#

I couldn't get the red axis to go through the right

leaden ice
#

red axis is going to the right (the object's right)

jaunty needle
#

ahhh

#

yeah that checks out

obtuse silo
#

I made a small tool to align stuff in my scene, bu I can't find how do I make the button (when the tool is docked) in two parts,
one Align button, and the other to show the tool settings, much like all the other Overlay tools.

mental sigil
#

Can someone help me figure out why my collision event functions are not being called?

#

Here is my player:

#

And here is the building I want to collide with

#

And this is the building script, and neither collision events get called

#

Even when I drag another building through it (I can drag them with the mouse) or move the player through it

#

Is it an issue for collision detection if I directly move the transforms?

lilac sonnet
mental sigil
#

Oh, I see and what would I do if I just want to check if they are colliding but I dont want them to push eachother around

lilac sonnet
#

Kinematic body types only move under explicit control (i.e., you'd have to write code to make it react to a collision "naturally")

mental sigil
#

But from what I read kinematic bodies dont trigger collision events either

lilac sonnet
#

IIRC they do if you check the simulated box on the component itself

mental sigil
#

Okay so my whole thing right now is that I want to use collisioin detection to find out if the user can place a building where the mouse is

#

Which I wanted to do by adding colliders and as you drag the building around and I use these collision events to check if the spot is clear

lilac sonnet
#

Is there a reason they’re static outside of just not moving? If that’s the case, I still think a Kinematic body type would cover it.

gray mural
#

Does somebody to know if it's possible to get first line's position of TMP_Text even when it is empty?

#

It's easy to do, when there's written something, but not with empty one

#

Or should I consider changing TMP_Text script?

latent latch
#

Perhaps use some whitespace placeholder?

gray mural
#

but it doesn't work in my case

gaunt blade
#

Hey, wondering if someone can explain why I'm getting an error. Here's some snapshots of my code as well as the error message I'm getting

#

As far as I can tell I intantiated my objects correctly, yet it's saying there's no reference to said objects. I'm kinda confused why.

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.

gaunt blade
#

Alright, I'll just go to a C# specific discord. Thank you!

gray mural
gaunt blade
#

The code is generating a NullReferenceException. It's not using any Unity specific libraries, it's all code I wrote myself. I'm sure a discord channel that specializes in C# specific stuff can answer it just as well as anyone here.

#

Thank you though.

simple egret
#

Yeah it's more of a general execution error, but as you're using Unity you'll probably get redirected to this server once they see the Unity console

gaunt blade
#

Guess I'll see. 🤷‍♀️

gray mural
gaunt blade
#
public Polygon(List<Vector2> vertices)
    {

        if (vertices.Count == 0) {  return; }

        for (int i = 0; i < vertices.Count; i++)
        {
            if (i == vertices.Count - 1)
            {
                edges.Add(new Line(vertices[i], vertices[0]));
                return;
            }
            Debug.Log("test");
            Debug.Log(vertices[2]);
            edges.Add(new Line(vertices[i], vertices[i + 1]));
            Debug.Log("test2");
        }
    }
#

Welp

#

That didn't work

#

There we go

steep herald
#

i + 1 will fail on last index

#

ah nvm

gray mural
gaunt blade
#
        {
            Debug.Log("Did I get here?");
            generateCicumcircle();
        }
simple egret
#

It fails before that, error is on line 27

gaunt blade
#

It calls the base class constructor

gray mural
#

show verticles that you set

#

as parameter

gaunt blade
#

So you want me to show you the instantiation of the Triangle object?

simple egret
#

Line 27, what is it

gray mural
#
public Polygon(List<Vector2> vertices)
#

verticles

#

what do you set here?

gaunt blade
#

There's no "l" in that. It's "vertices"

gray mural
simple egret
#

"Probably"

#

Show line 27 please

gray mural
# gaunt blade There's no "l" in that. It's "vertices"
List<Vector2> verticles = new(); // show me this !

//
//

public Polygon(List<Vector2> vertices)
    {

        if (vertices.Count == 0) {  return; }

        for (int i = 0; i < vertices.Count; i++)
        {
            if (i == vertices.Count - 1)
            {
                edges.Add(new Line(vertices[i], vertices[0]));
                return;
            }
            Debug.Log("test");
            Debug.Log(vertices[2]);
            edges.Add(new Line(vertices[i], vertices[i + 1]));
            Debug.Log("test2");
        }
    }
gaunt blade
#

That line you commented doesn't exist?

#

I'm not sure what you're talking about

#

There is no "verticles" variable

simple egret
#

edges can also be null here, can you not speculate and tell them to actually show the line 27?

steep herald
#

can you show us the line generating the error

gray mural
gaunt blade
#

edges.Add(new Line(vertices[i], vertices[i + 1])); That is the line generating the error

simple egret
#

Edges is null

gray mural
#

show edges than

#

I thought verticles is null though

steep herald
#

it's still vertices

gray mural
simple egret
#

If it was, it would have thrown in the first if statement that checks for its count, though

#

Vertices takes no L

steep herald
#

oh I'm absolutely not saying verts list is null

gray mural
#

@gaunt blade it gonna take too long, just full code, please

gaunt blade
#

Thank you.

#

Very dumb mistake on my part.

#

Didn't instantiate it.

faint scroll
#

whats an algorithm to generate seemless perlin noise on a sphere? i use a 2d texture:

private void Pixelreader(){
    Texture2D image = new Texture2D(size, size);
    gameObject.GetComponent<MeshRenderer>().material.mainTexture = image;
    for (float i = 0; i < image.width; i++)
    {
        for (float j = 0; j < image.height; j++)
        {
            float Perl = Mathf.PerlinNoise(i * perlZoom,j * perlZoom);
            Color color = Color.green;

            if (Perl < thresh)
                color = Color.blue;

            //Color pixel = new Color(Perl, Perl, Perl) ;
            image.SetPixel((int)i, (int)j, color);
        }
    }
    image.Apply();
}

But it isnt seemless, as shown below:

celest moss
#

Is there a way to revert a scriptable Object to the original values?

potent sleet
celest moss
potent sleet
#

when you change a SO it stays changed

#

no

#

you're changing the whole asset

#

it's stored on your disk not in memory

#

big reason SO not meant for mutable data

#

you typically copy the data to use then manipulate it in a separate class

simple egret
#

Plus, in builds it does not behave the same (it's not saved between two executions)

#

So using it as a mutable data container is a big no-no

potent sleet
#

if you're using this as a save system, don't xD

celest moss
potent sleet
#

if you want to revert back just make it a regular class / struct

#

and use prefabs for preset values

mellow hill
celest moss
mellow hill
#

That is not really what they are intended for though

#

What sort of system are you building?

celest moss
potent sleet
regal epoch
#

would it be possible that c# is too fast? Im trying to destroy the childs of an empty game object. but sometimes it just skips one for some reason

celest moss
potent sleet
#

think SO as preset

latent latch
#

If you're going to write to scriptable objects, always make instances. Doing it this way would also allow you to 'revert' to the original values depending if you want to create a new instance or just read the original values.

potent sleet
#

it can say , this Stat holds "attack 20, defense 10 etc.."

but in the enemy class you copy those stats into the class to change at runtime

mellow hill
# celest moss but these values can be changed in the runtime :d

What I would do the that is have a seperate save system, let's say you save stats to a JSON file "Stats.JSON", then on load you can read that JSON file in at runtime and use that data to dynamically create ScriptableObjects. This way you can save/load from the JSON file. If you wanted purely a ScriptableObject approach, just have the stats but there are ways to use apurely ScriptableObject approach as well such as copying values from the enemies into the scriptable objects and keeping them up to date

dawn nebula
#

How do I modify the properties of a Sprite asset from code? Looking to change things like SpriteMode and shit.

dawn nebula
#

preset?

#

I have a sprite sheet with a ton of sprites. I have a json which describes what region of the sprite sheet contains what sprite.

dawn nebula
#

So I want to programmatically define the many sprites in that sheet.

potent sleet
#

I recall this is how I had to do it . I made a script that makes screenshots out of scene view but it was saved as texture and not sprite so I had to make a script + preset to change ALL the images that get put into that folder automatically to sprite type

jaunty needle
# leaden ice that looks fine

Hey so I have this piece of code which... works but the object moves and keeps jittering for some reason:

    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;

            Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);

            transform.rotation = Quaternion.LookRotation(newDirection);

            yield return null;
        }
    }

#

For context if anybody else wants to help I'm trying to get an object to look at me but for some reason here ti moves too

gray mural
gray mural
jaunty needle
gray mural
gray mural
#

try to increase 4th parameter

#

from 0f to 10f, for example

jaunty needle
#

Thing is I just followed the documentation which did the same thing

#

What's increate?

gray mural
jaunty needle
jaunty needle
leaden ice
#

That parameter isn't relevant at all

gray mural
jaunty needle
gray mural
#

The maximum allowed change in vector magnitude for this rotation.

leaden ice
#

I would guess the issue has to do with another component on the object or something

jaunty needle
#

The components

leaden ice
#

Although for this use case I would probably be using Quaternion.RotateTowards

#

Yeah the Rigidbody

gray mural
jaunty needle
leaden ice
#

If you're rotating a Rigidbody you'll want to:

  • do the rotation in FixedUpdate
  • use RB.MoveRotation
  • enable interpolation on the body
jaunty needle
#

Aha

#

I missed that thank you

#

Do I use the same technique I used here for rb.moverotation?

    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;

            Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);

            transform.rotation = Quaternion.LookRotation(newDirection);

            yield return null;
        }
    }
#

Thing is I'm doing this in a coroutine

warm stratus
#

Hey, how do i do to make the UI element the biggest that it cans in the anchors that i set?

gray mural
#

with Alt key

gray mural
gray mural
spiral robin
#

How can I acces the fill float on my material via code? The float comes out of a custom shader.

gray mural
warm stratus
#

i wan t something like this

gray mural
leaden ice
gray mural
#

that's what you asked for I guess ??

#

..how do i do to make the UI element the biggest that it cans..

jaunty needle
gray mural
warm stratus
leaden ice
jaunty needle
#

Ahh so I put the code in fixed update?

#

Could you explain further please

warm stratus
gray mural
#

these are offsets

#

that appear in stretch

warm stratus
wise agate
#

Does anyone know how to get the left and right triggers. if (Input.GetKey(KeyCode.Space)) throttle += throttleIncriment; but referencing the left or right trigger on a controller instead of the Space Key

jaunty needle
leaden ice
gray mural
wise agate
warm stratus
leaden ice
#

That's the only thing it works with in fact

gray mural
wise agate
wise agate
leaden ice
leaden ice
warm stratus
warm stratus
gray mural
jaunty needle
warm stratus
gray mural
#

it's like

smth.width = .4f * Screen.height;
warm stratus
warm stratus
wise agate
warm stratus
#

thks for help 👍

buoyant crane
jaunty needle
warm stratus
#

@gray mural oh no 🤣 i found it it was just that

warm stratus
jaunty needle
#

It's still moving towards me :(

gray mural
jaunty needle
#
    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;

            Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);

            Quaternion newRotation = Quaternion.LookRotation(newDirection);

            rb.MoveRotation(newRotation);

            yield return new WaitForFixedUpdate();
        }
    }
#

I changed it

visual glade
#

could anyone help me with this error? I got it while trying to build.

An asset is marked with HideFlags.DontSave but is included in the build:
Asset: 'Library/unity editor resources'
Asset name: DefaultReflectionForPrefabMode

I tried looking in library but I don't have a unity editor or defaultreflection.

gray mural
gray mural
dire coral
#

how can i make local multiplayer work

dire coral
#

local

#

not network

gray mural
dire coral
#

i asked how i can make a local multiplayer. local means 2 people on 1 pc and keyboard

gray mural
scenic coyote
#

I want to check if my player is grounded, and I'm using this code:

bool is_grounded = Physics2D.CircleCast(ground_check.position, 0.5f, Vector2.down, 1f, 6);

where ground_check is an empty placed at the feet of my character. Thing is, I don't know what to do with the distance attribute, in this case, the 1f. Any help would be appreciated

gray mural
leaden ice
scenic coyote
gray mural
wind palm
gray mural
#

so you should check is collision's tag is Ground and than do stuff

gray mural
wind palm
#

AKA a platform

gray mural
wise agate
gray mural
#

if they do not have ground walls, using OnColisionEnter should be better

scenic coyote
wind palm
scenic coyote
#

Ah, okay. Let me try then

gray mural
#

cause I am not sure

wind palm
#

As for why you're not "grounded", I'd need to see more information (i.e the position of your ground check)

scenic coyote
#

Yeah I was wondering, if my ground layer is on layer 6, do I input 6? or 7 because it counts from 0?

gray mural
#
int groundLayer = 6;
LayerMask groundLayerMask = 1 << groundLayer;
gray mural
#
bool isGrounded = Physics2D.CircleCast(groundCheck.position, 0.5f, Vector2.down, 1f, groundLayerMask);
scenic coyote
#

what's the reasoning behind doing a bitshift?

gray mural
#

also make sure distance is enough

wind palm
gray mural
wind palm
#

The inspector will let you check the layers you want to check 🙂

scenic coyote
#

well, I just tried a mix of both solutions, I used overlapCircle and the 1 << 6 for layer mask and it works. Altough I still would like to know why we are bitshifting?

wind palm
#

By doing 1 << 6 you're saying the 7th bit should be 1.

scenic coyote
#

Ohh I see. Well thanks a lot you both :D

gray mural
#

Does anyone know where TMP_LineInfo.lineExtents is changed?

#

I just need to find this in unity's code

#

And I don't see any methods in TMP_Text that do it (have printed them)

#

it's just min = Vector2(0, 0) and max = Vector2(0, 0), when nothing was typed in TMP_Text yet

visual glade
# gray mural your should reimport your asset

reimporting my assets didn't do anything. Looking online they told me to search in project for "t:Prefab DontSave" and all the related ones, but that didn't come up with anything either.

cobalt gyro
#

does anyone know what could cause this type of glitch

potent sleet
#

looks like clear flags insnt clearing

#

or w./e flags on cam

heady iris
#

yeah, hall of mirrors moment

#

camera settings are wrong. this is what you'd adjust in the HDRP.

cobalt gyro
#

thanks

forest bluff
#

who need help

#

i am pro

celest moss
#

Hey im struggling a bit to implement a clean solution for ObjectPooling for GameObjects which all inherit the baseClass Enemy but are different prefabs and should be pooled in different ObjectPools. Ideally i would only provide the list of all enemy types.

forest bluff
#

this will solve all your problems

heady iris
#

don't spam

forest bluff
#

how is that spamming

potent sleet
#

offtopic is spamming in away

forest bluff
#

no its not spamming is repeatedly saying something

potent sleet
#

<@&502884371011731486>

heady iris
#

i've never been accidentally pinged!

potent sleet
#

myb

heady iris
#

lol

potent sleet
#

hit c too quick

heady iris
#

i was already looking at the chat.

potent sleet
#

w/e they probably got auto kicked by Dyno

vagrant blade
#

!warn 833097364704591924 There is no off topic here.

tawny elkBOT
#

dynoSuccess Bossmanduty916#3210 has been warned.

vagrant blade
#

Oh wait, this isn't your first rodeo.

#

!ban save 833097364704591924 Banned for spamming. wwi_wave_yellow

tawny elkBOT
#

dynoSuccess Bossmanduty916#3210 was banned.

latent latch
wanton marsh
#

yo

#

i need help

latent latch
#

Benefits of the first way, single queue and can instantiate all the objects you need early on. Benefits of the second way, less component/data injecting, and syncing if needed

wanton marsh
#

everytime i try to load my project it just pulls the unity bug report

gray mural
wanton marsh
#

and i uninstalled the unity hub too

#

it still dosent work

#

please help

heady iris
#

Oops

#

Wrong reply. You get the idea

#

damn phones

gray mural
#

@visual glade

soft shard
#

Im testing some code, and im not sure I understand whats going on, ive decided to use the ScriptableObjects InstanceID instead, my original approach was to make a public property and generate a GUID with each scriptable object once, and be able to use that in a Dictionary elsewhere:

public SomeSO : ScriptableObject
{
public string ID {get {return id;} }
string id;

void OnEnable()
{
if(string.IsNullOrEmpty(id)) {id = new GUID();}
}
}

This works fine, though whenever the project is re-opened, OnEnable will get called again on every SO (which makes sense, and is fine), but for some reason I dont understand, it will also re-assign a new ID, as if its just reset to null when Unity closes, why might that be? I tried setting the SO to dirty as well and AssetDatabase re-saving the file - the assets instance ID doesnt change between re-launches so I figured ill just use that instead, though id like to understand why this GUID approach may not have worked?

celest moss
cobalt gyro
wanton marsh
#

yo hello

#

can anyone help please

heady iris
latent latch
#

You can also make prefrabs of a full constructed enemy, such that no extra work is needed when called

#

Ideally, queueing the base type is what you want to do in most cases

visual glade
gray mural
visual glade
#

np, I'll go back to the try and true method of saving a copy and then go back and slowly delete things until it works.

visual glade
gray mural
#

and also makes it easy to return your project to its previous versions

visual glade
#

Ah, yea I'll definetly need to try that out, thanks.

jaunty needle
#

Hello guys, I have a problem with getting an rigidbody object to look at the player when it comes within a certain range
This is the code that I use:

    {
        if(other.CompareTag("Player"))
        {
            StartCoroutine(TurnTowardsPlayer());
            print("Player is detected");
        }
    }

    IEnumerator TurnTowardsPlayer()
    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;

            Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);

            Quaternion newRotation = Quaternion.LookRotation(newDirection);

            rb.MoveRotation(newRotation);

            yield return new WaitForFixedUpdate();
        }
    }
#

But instead it doesn't just rotate to face the player but instead moves towards it too

potent sleet
jaunty needle
#

Yes, these are the components:

potent sleet
#

like does it not move

harsh ridge
#

does anyone know how i can change my web swinging, currently to pull towards the web you pull down on the trigger but i want it so you have to pull on the web and then let go? anyone know how i can do that? in vr?

jaunty needle
#

Wait I noticed this

potent sleet
#

does it still move

jaunty needle
dawn nebula
#

So I have some animations for a sprite. The state of my sprite is handled completely by scripts. I don't want some complex state machine controlling the animations. I want all transitions to be instantaneous. How do I set up the animator to achieve this behaviour?

jaunty needle
latent latch
potent sleet
uneven cloud
#

Does someone has been working on a game and has been using Steam Inventory using Steamwprks.NET? (please reply with ping)

uneven cloud
latent latch
dawn nebula
#

Ah there's "Animator.Play"

jaunty needle
#

Apparantly I shouldn't have used this other transform it was weird

jaunty needle
#

So here

#

I have the rbcharactercontroller

#

and cameraholder

#

I used the cameraholder instead which is weird I don't wanna get into it

potent sleet
#

oh alright, just didn't know why that method moves it too but reading the docs now it makes sense why it does

#

i never used it before

latent latch
#

you'll want to loop stuff on the clip itself if not in the animator such as running

visual glade
late basin
#

hi. I can't seem to get the freeze Z rotation constraint to work. I have a cube with a rigidbody that I can tilt up and down and rotate left and right using AddTorque. If I rotate while x=0, it works. if I tilt first, then rotate, it changes the z-axis. I have Freeze Rotation : Z checked. How can I make the cube spin around the Y axis in world space instead of tilting on the z-axis? This is how I'm imparting the rotations:

private void ApplyYaw() {
    Vector3 yawForce = yawPower * (yawPercent / 100) * Vector3.up;
    _rb.AddTorque(yawForce);
}

private void ApplyPitch() {
    Vector3 pitchForce = pitchPower * (pitchPercent / 100) * transform.right;
    _rb.AddTorque(pitchForce);
}

What am I missing?

random gulch
#

Theoretically would movetowards or NavMeshAgent be more resources intensive

leaden ice
#

It's kinda like asking whether the Pythagorean theorem or Google Maps is more resources intensive

random gulch
#

Fair enough

#

Just curious because I am planning to move a bunch of objects

jaunty needle
#

Guys why does my detection happen before I'm actually on the object

#

        if (Physics.Raycast(ray, out hitInfo, range))
        {
            if(hitInfo.rigidbody != null)
            {

                MeshRenderer objectMesh = hitInfo.rigidbody.gameObject.GetComponent<MeshRenderer>();
                if (objectMesh != null)
                {
                    objectMesh.material.color = Color.green;
                }

            }

        }
potent sleet
#

also that ray might be hitting itself

#

use layers i suppose

static matrix
#

can I post a scripting joke or is that not allowed

lean sail
dawn nebula
#

Anyone know how to create an AnimatorController asset and apply AnimationClip assets to it?

oak plover
#

anyone know why hatebin doesnt make a link?

potent sleet
oak plover
#

yes

potent sleet
delicate zinc
#
    public class DetatchChildrenOnDestroy : MonoBehaviour
    {
        public Transform[] selectedChildren = Array.Empty<Transform>();
        public UnityEvent OnChildrenDetached;
        private void OnDestroy()
        {
            foreach (Transform t in selectedChildren)
            {
                t.parent = null;
            }
            OnChildrenDetached?.Invoke();
        }
    }```
i have this small script that i'm using for VFX, mainly for detatching particle systems when it's parent gets destroyed so the particles can dissipate and destroy the particle system when the system stops.

However, i'm getting this message sometimes when i change scene

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

Is there a way i can avoid this, aside from well, not putting this OnDestroy?

static matrix
#

my scripts be like:

#

sorry
but it was just too relatable

vague jolt
#

So i have some structures and you can connect cables to do them. The connection points are fixed point on the structure. Whats a good way to move these points when i rotate the structure ? The problem is that when i rotate the structure i don't rotate it i change the sprite to another one. Should i store the position of each connection point for each of the 4 rotation or do something else ?
this is the strcuture btw and you can see it has 4 connection point
so it would be a tolta of 16 sets of coordinates
there must be a better way

vague jolt
steep herald
#

Quick Q, I have a class and there are 2 instances in the scene. Class contains a coroutine with the following yield instruction, followed by some code
while (Time.time < some target) yield return null;
Let's pretend the coroutine's duration is 0.1 second. Instance A starts the coroutine, now 0.05 seconds later, instance B starts the coroutine, and now pretend GC kicks in/theres a spike for whatever reason and both coroutines end on the same frame. Is the code following the block above guaranteed to be executed in instance A first, or is that not guaranteed?

vague jolt
#

but still i would not count too much on that

steep herald
#

hm, ok well pretend 2 coroutines are called the same frame, on the same class and the same mono, is the first coroutine invoked guaranteed to execute its code before the second every frame?

#

When both coroutines yield every frame until condition X is met

vague jolt
steep herald
#

thank you @vague jolt

vague jolt
lean sail
vague jolt
#

they are bit ofset from where they are supposed to be, still if you say to manually write the coordinates thats probably the best idea i guess

lean sail
#

Since you change the sprites, the rotation might not be 100% lined up yea. The sprites you've shown look quite different and not like the same object rotated

#

Really it's just 4 collections of 4 points, assigning that is going to be way quicker and the memory used is so insignificant

warm shadow
#

So im trying to get KeywordRecognizer to work with a simple test, but it doesn't recognize anything i say, here is the code:

private KeywordRecognizer keywordRecognizer;
private Dictionary<string, Action> actionMap = new Dictionary<string, Action>();

private void Start()
    {
    actionMap.Add("up", test);
    actionMap.Add("Up", test);

    keywordRecognizer = new KeywordRecognizer(actionMap.Keys.ToArray());
    keywordRecognizer.OnPhraseRecognized += OnRecognizedSpeech;
    keywordRecognizer.Start();

}

private void test()
{
    //Do something
}

private void OnRecognizedSpeech(PhraseRecognizedEventArgs speech)
{
    Debug.Log(speech.text);
    actionMap[speech.text].Invoke();
}

It never debugs anything...

mossy snow
warm shadow
#

there is no error, it just never detects anything, i think it might have something to do with my headset. Dont know id it knows which microphone to use... But i have no idea how to fix it

mossy snow
#

docs are a bit light. You are on windows 10?

warm shadow
#

yes

mossy snow
warm shadow
#

i did consider that, but it doesn't mention anything about the microphone in the documentation and i also found a tutorial where i did the exact same.

mossy snow
#

maybe you should test it anyway, just to make sure your app is actually receiving microphone data to begin with

warm shadow
#

Yeah, i have tested the microphone and it does receive the data, i did that for an earlier attempt at voice commands

#

I do also have this warning in the build settings, but not sure if it is related

vague jolt
#
public class ConnectionsV2 : MonoBehaviour
{
    [Serializable]
    public class References
    {
        public List<GameObject> structures = new List<GameObject>();
        public List<GameObject> cables = new List<GameObject>();
        public List<int> connectedTo = new List<int>();
    }

I have the class references in teh class ConnectionsV2

    void deleteConnections() 
    {
        foreach (KeyValuePair<string, ConnectionsV2.References> entry in connectionsV2.references)
        {
            foreach(GameObject cable in entry.cables)
            {

            }
        }
    }

Why for this i get the following error : KeyValuePair<string, ConnectionsV2.References>' does not contain a definition for 'cables' and no accessible extension method 'cables' accepting a first argument of type 'KeyValuePair<string, ConnectionsV2.References>' could be found (are you missing a using directive or an assembly reference?)

heady iris
#

well, yeah, entry is a KeyValuePair

#

it's not a References

vague jolt
#

so how do iterate between the cables ?

heady iris
#

get the value out of the key value pair

vague jolt
#

how ?

#

entry.ConnectionV2.References ?

#

got it entry.Value.cables

heady iris
#

yes

#

pay attention to your types

#

foreach (KeyValuePair<string, ConnectionsV2.References> entry in connectionsV2.references

#

entry is a KeyValuePair<string, ConnectionV2.References>

next seal
#

Getting these errors and I dont really know why
I'm using URP and made a custom shader and its not working

potent sleet
next seal
#

my bad I thought that wasnt for errors

vague jolt
#
Blueprint saveStructure(List<GameObject> structures)
    {
        Blueprint save = new Blueprint();
        save.entities = new EntityObject[structures.Count];

        for(int i=0; i<structures.Count; i++)
        {
            save.entities[i].entity_number = i;
            save.entities[i].name = structures[i].tag;
            save.entities[i].position = new PositionObject();
            save.entities[i].position.x = structures[i].transform.position.x;
            save.entities[i].position.y = structures[i].transform.position.y;
            save.entities[i].direction = structures[i].GetComponent<RotateSprite>().rotation;
            save.entities[i].connections = new ConnectionObject();
            save.entities[i].connections.first = new ConnectionPointObject();
        }

        return save;
    }

Here i get this error
NullReferenceException: Object reference not set to an instance of an objectSaveFileGenerator.saveStructure (System.Collections.Generic.List`1[T] structures)

#

the error is on this line : save.entities[i].entity_number = i;

quartz folio
#

You have nothing assigned to save.entities[...], unless you're using structs

leaden ice
#

Yep^ Reference types (classes) default to null

#

So your array is full of nulls until you populate it

#

e.g. your code is expected to look like:

        for(int i=0; i<structures.Count; i++)
        {
            EntityObject eo = new EntityObject();
            eo.entity_number = i;
            eo.name = structures[i].tag;
            ... // etc
            save.entities[i] = eo;
        }
#

(note rather than accessing it through the array a million times, you can just populate the object and then add it to the array at the end, as per my example)

#

I would also consider making a constructor for EntityObject like:

public EntityObject(int number, Structure structure) {
  // populate all the fields in here, instead of externally
}```
#

then your loop can be even simpler. Something like:

for(int i=0; i<structures.Count; i++)
{
    EntityObject eo = new EntityObject(i, structures[i]);
    save.entities[i] = eo;
}```
vague jolt
quartz folio
vague jolt
#

like i do that an now the variable exists, why can't i say this save.entities[i].entity_number = i;

vague jolt
quartz folio
vague jolt
#

ahhh i got it do i need to do save.entities[i] = new something ?

halcyon venture
#

help

quartz folio
#

And don't cross-post

halcyon venture
#

srry

leaden ice
#

Can you add some words to describe what we're looking at?

#

I just see a triangle and some numbers

#

which line

#

and wdym based on x axis

#

a triangle is not a line

#

this still doesn't clarify anything

#

what exactly is the information you have and what information are you looking for?

#

I know it seems obvious to you but we have no context

#

for what?

#

you are not explaining the issue well, hate to say

#

It is unclear in this picture what informatioin you are starting with and what you are trying to create/calculate

wide barn
#

that makes no sense

leaden ice
#

You can't just say "I just want a function" without saying what you want the function to do lmao

#

cool story but like

#

what do you want the function to do?

#

just what?

#

lol

#

say what you are thinking

#

what is a "triangle like line"

#

that makes no sense

#

me neither

#

Imagine I said to you. Hey, I want a function that does this:

#

How do I do that?

#

you would have no idea what I'm talking about

#

that is what you have done to me

#

it's not the complexity

#

it's the fact that you didn't explain what you actually want

#

except for "triangle like line" which doesn't make sense

#

make which line?

#

maybe start by highlighting the line you are interested in

#

in the diagram

#

there are 4 black lines here

#

counting the dotted ones

#

there are two

#

and what do you mean by a "line" exactly? Do you want a vector? Or two points denoting the line segment?

#

two black lines

#

a math function needs to have some kind of result

#

I'm asking what kind of result you want

#

uhhh, no not in any universe is that one line lol

leaden ice
#

you can't just say "a line"

#

I mean as far as I can tell all you want is how to make a vector with an x/y coordinate

#

and that's just new Vector2(x, y)

#

I feel like you are a robot sent here to confuse people

#

doing a decent job

#

first you wanted a math function now you want an image

wide barn
#

soo you want to make a line between 2 points, then reflect that line?

leaden ice
#

Clearly I cannot help you

#

i didn't ask that at all

#

I asked what you want the math function to return

#

Actually I think what you want is this

#

well actiually

public float MyFunction(float x) {
  return Mathf.PingPong(x * 2);
}```
#

that will give you the graph you shared

#

the dotted black line confused the hell out of me

#

ok sorry - idk your explanation was not grokking in my head

magic storm
#

So ive been dealing with this issue today, whenever i create a script in unity, I always get the 'no monobehaviour in script' error. I re installed every version of unity including the hub and the issue persists.

#

even with an empty script

lean sail
magic storm
#

I just created it and thats it

lean sail
#

i cant see the full name, but assuming you didnt rename it, do you have any errors in console

magic storm
#

no errors

#

all i did was create script, didnt change anything

leaden ice
#

especially including the top right

karmic cape
#

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

magic storm
#

omg i seriously didnt think to check it, thanks guys i just needed somone else to overview it lmao

karmic cape
#

hey peeps anyone any idea why this script would not work no errors show

leaden ice
#

you have to explain what you want or expect the script to do, and what it's doing instead.

karmic cape
#

the script should change the skybox based on time it changes to the 1st skybox csRenderSettings.skybox = SkyNight; but it dosnt change from that

leaden ice
warm wren
karmic cape
#

iv found the issue its restarting the blend for every frame

#

idk how else to handed it other than the if statment

dusk apex
#

Are there any errors?

rough crown
#

Ok so I have a script that doesn't derive from MonoBehaviour but I want to see it in the editor to drag stuff in. Sure there is AddComponent() but it only happens at Runtime. Is there a way to "show" non-Monobehaviour derived classes in the editor? Or are there at least any workarounds?

#

Hmmm. It plain works

#

Might mess around a bit

soft shard
# rough crown Ok so I have a script that doesn't derive from MonoBehaviour but I want to see i...

Sounds like you want a serialized class? Something like:

[System.Serializable]
public class SomeNonMono
{
public int someNumber;
}

public class SomeMono : Mono //this could also be a ScriptableObject if it doesnt need to exist in the scene
{
public SomeNonMono data;
}

Otherwise, you may have to create a custom property drawer or custom editor with an attribute for that class and essentially tell the inspector how that class should be displayed when selected

rough crown
soft shard
potent sleet
#

prob mistaken 😛

sharp oak
#
{
   
   public float moveSpeed = 5f;

   public Rigidbody2D rb;

   Vector2 movement;


   void Update()
   {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Veritcal");

   }

   void FixedUpdate()
   {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
   }

} ```
#

Hi, for some reason I keep getting this error when starting my game?

sharp oak
#

Really? I checked that several times to make sure it was spelled right.

#

Thanks for showing how idiotic I can be lol

potent sleet
#

strings are just tricky like that xD

grand karma
#

Hi, I'm currently having an issue using the following package.

https://assetstore.unity.com/packages/templates/packs/dice-pack-light-165#description

I've looked through how it typically works, found the helper methods referenced in the READ-ME, but I believe that the pre-fabbed dice are invisible which I do not understand. I am somewhat of a beginner to Unity so I'm probably just missing something simple but the package had a helper method for rolling the dice which should've handled everything. I noticed that the clones do appear, however, they show as greyed out which I will show in an image below. I've even tried using some of their working demo in order to make it work and it simply will not show.

My code is as follows (made for a test outside of my main project):

public class NewBehaviourScript : MonoBehaviour
{


    // Start is called before the first frame update
    void Start()
    {
         
    Dice.Roll("4d6", "d6-black", transform.position, new Vector3(1,1,1));
             
    }
    

    // Update is called once per frame
    void Update()
    {
        
    }
}```
I've also attached the readme instructions for this asset in case anyone needs context: https://pastebin.com/gg7Ta1B9

Use Dice Pack Light from WyrmTale Games to elevate your next project. Find this & more Packs and templates on the Unity Asset Store.

#

wait im so confused

#

when i use a check mark on them they show up

#

but why do i need to do that outside of my code

buoyant crane
grand karma
#

they all appear to be active

buoyant crane
#

huh weird

grand karma
#

it's also strange because they included a demo scene which works fine, but even if I copy code to mine it won't work

#

I'm kinda frustrated bc I'm experienced coding in java and python in the past but i just cant get this to work

vague slate
#

How can I get a reference to SRP feature of specific type?

obsidian saddle
#

Is there any way to show Sprite arrays in the inspector? I've tried [SerializeField] but that didn't work either. Am I missing something?

buoyant crane
#

Sprites should work so there’s something amiss

obsidian saddle
grand karma
#

hmm for whatever reason I had to handle the activity myself but it now works

obsidian saddle
buoyant crane
obsidian saddle
#

nope

#

oop

#

wait yes

#

i forgot a semicolon 💀

#

sorry to both lmaooooo

#

*bother

obsidian saddle
simple edge
#

By default I always hide warnings, might be worth doing as well

obsidian saddle
#

yeah i should rlly do that, they never seem to say anything genuinely helpful lol

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.

viscid parcel
#

So I'm back and with a new issue so i beg for help, I cannot figure out how to check for which raycast would be closer, the idea of this code is to be the check for my AI if my player is close enough, however so that they don't detect my player through walls I added the hardplatform raycast but my issue is if the player is close to a wall or floor the enemies will not continue tracking the player. its in unity2D btw

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

public class SC_AISensor : MonoBehaviour
{

    public Transform PlayerTarget;
    public float pDistance;
    public LayerMask Player;
    public LayerMask Hardplatform;
    
    void Update()
    {
    }
    public bool DetecManager()
    {
        Vector2 position = transform.position;
        Vector2 target = PlayerTarget.position;
        target -= position;
        target.Normalize();

        RaycastHit2D DetectBlock = Physics2D.Raycast(position, target, pDistance, Hardplatform);
        RaycastHit2D Detection = Physics2D.Raycast(position, target, pDistance, Player);
        Debug.Log(Detection.collider.tag);

        if (DetectBlock)
        {
            return false;
        }
        else if (Detection)
        {
            return true;
        }
        return false;
    }
}```
lean sail
mellow sigil
#

Why do you make two raycasts? Make one and check what it hits

viscid parcel
#

i have to do two when using layermasks no?

mellow sigil
#

No, you can have multiple layers in a mask

#

that's the entire point of masks

lean sail
#

in the inspector, doesnt it let u choose multiple options in the layermask anyways?

quartz folio
#

Yes it does

viscid parcel
quartz folio
#

No, have one layer mask with both layers in it, and one raycast

#

whatever it hits will be the thing that was closest

gray mural
coral talon
#

Hi. After I connected my project with git, any older files can't refer to the new ones.

viscid parcel
#

just found how to do what you meant

#

a lot of my code is much more cursed considering this is a thing

quartz folio
viscid parcel
#

Thank you so much @lean sail @mellow sigil @quartz folio

quartz folio
quartz folio
# coral talon

One of your scripts is in an Editor folder, so it's in the editor assembly

#

the other isn't, and cannot reach the editor assembly

coral talon
#

I thought they all should be in global namespace

quartz folio
#

They are, the assemblies are different.

coral talon
#

How to address this issue?

quartz folio
#

You're presumably trying to use this serialized scriptable object outside of the editor

#

so don't put it in a folder named Editor