#archived-code-general

1 messages ยท Page 68 of 1

leaden ice
#

does dspTime not incorporate that already?

sterile tendon
#

oh well my implementation just changes the speed of the audio playing taking into account its base tempo and corrects the pitch

#

since I want to incorporate all sorts of different songs I can't just globally change it

#

has to be per stem

#

oh wait would it be better to store all the stems at the same bpm/key and shift it globally actually?

#

might be bad for audio quality but I doubt many people would notice

leaden ice
potent sleet
#

machine created humans so it can create itself

sterile tendon
#

thanks!

candid trench
#

Alright, now i feel silly. How do i raycast on a UIelement?

#

or get whatever the mousepointer is currently hovering?

potent sleet
candid trench
#
            var eventData = new PointerEventData(EventSystem.current);
            eventData.position = Input.mousePosition;
            var results = new List<RaycastResult>();
            EventSystem.current.RaycastAll(eventData, results);
            if(results.Where(r=>r.gameObject.layer == 6).Count() > 0)
            {
                Debug.Log(results[0].gameObject.name);
            }
#

using this?

#

wait, did i forget to set the layer..

#

noo, thats not it.

simple egret
#

Tip, you can shift the lambda in the Count, and get rid of the Where

candid trench
#

what? like this?
results.Count(r=>r.gameObject.layer == 6) > 0

simple egret
#

Yup

candid trench
#

neat!

#

the code still doesnt work tho .. meh

potent sleet
#

is the code running?

candid trench
#

it is indeed running

#

well okay, now it worked

#

sigh.

#

i swear, this place is great if you wanna make yourself feel silly

#

whats the difference between ?
EventSystem.current.RaycastAll(eventData, results);
GameObject.Find("Canvas").GetComponent<GraphicRaycaster>().Raycast(eventData, results);

sterile tendon
#

I just figured I should run the idea by you first

soft shard
# candid trench whats the difference between ? `EventSystem.current.RaycastAll(eventData, result...

https://docs.unity3d.com/560/Documentation/ScriptReference/EventSystems.EventSystem.RaycastAll.html

https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-GraphicRaycaster.html

Based on the docs, it seems like the EventSystem is global, and will use any and all raycasters base (which GraphicsRaycaster uses), while GraphicsRaycaster is specific to only checking for events on the Canvas its attached to, the only scenario I can think of is if you have multiple Canvases layered infront of eachother, you may also have multiple GraphicRaycasters for each canvas, you could use the graphic raycaster to check for hits on one canvas and not the other, or if you just want to know if there is any hit regardless of the canvas it belongs to, maybe the EventSystem makes more sense, but this is just a guess as I havnt had many use-cases for this myself

orchid bane
#

I have this purple emoji, green circle and white door sprites with the emoji one being placed in front of all other tho not by much. By only 0.01 or so. Sometimes emoji gets rendered UNDER the other two. Any ideas how to fix it?

#

It's a photo from the side

candid trench
#

Assuming the hashset only has one member, how do i get it?

        HashSet<Unit> selectedUnits = new HashSet<Unit>();
        //Some code to add units bla bla
        
        if (selectedUnits.Count == 1)
        {
            infoPane.transform.parent.gameObject.SetActive(true);

            string newInfoText = "Name: " + selectedUnits[0].name + "\n" +
                            "Faction: " + selectedUnits[0].faction + "\n" +
                            "Role:" + selectedUnits[0].role.ToString() + "\n" +
                            "Health: " + selectedUnits[0].hitPoints + "\n" +
                            "Damage: " + selectedUnits[0].attackDamage;
            infoPane.text = newInfoText;
        }
solemn raven
#

hey,
is it possible to check if pointer is still hovering over a button or not ?

neon plank
solemn raven
#

which handler is responsible for the pointer hover ?

#

?? some parts of the documents are missing in 2021 ??

#

I have version 2021.3 and it does have the Ipointer under UnityEngine.EventSystems

#

its weird the the documents has no reference to the UnityEngine.EventSystems for version 2021.3

solemn raven
#

but I still couldnt figure out how to check if pointer was still hovering on the button after clicking

left gale
#

Is it possible for a unity game to load and execute an assembly not built directly against the unity .net dlls but rather against some other .net standard profile ?

solemn raven
#

which event I need to run to see if the pointer is on the button ?

somber nacelle
#

IPointerEnter and IPointerExit

solemn raven
#

unless u exit the button then reenter

left gale
#

I don't really know much about it, but isn't there an property in the mouse event data for checking if it's a drag operation and what entity is handling it?

marble halo
#

why the hell is it that when i slide down the left slope, it's so slow

somber nacelle
#

probably friction. of course you haven't provided enough info to actually know for sure

marble halo
#
        {
            var normal = Quaternion.FromToRotation(Vector3.forward, player.hitNormal);

            player.velocity = Vector3.ProjectOnPlane(new Vector3(0, player.velocity.y, 0), player.hitNormal);
        }```
#

fyi im using a character controller

#
        {
            player.velocity.y += player.gravity * 3 * Time.deltaTime;
        }
        else
        {
            player.velocity.y = -2.5f;
        }```
#

the one on the right slides down fine

#

but the left one is so slow for some reason

#

because if i try to increase the speed multiplier in velocity.y it goes down the other too quick

#

so how do i fix this?

#

heres the script

somber nacelle
#

wouldn't you want to store the current gravity value in a separate float then use that when creating the projected Vector3? because as it is now you're resetting the x and z velocity every time you project the plane

marble halo
#

hmm maybe

#

ok i think i got it to work, now i need to figure out how to make it so the player can't push against the slope to slow down the sliding speed

rustic ember
#

Why are singletons considered bad?

somber nacelle
#

they are only bad if misused. but they introduce global state to the program. anything can access a singleton at any time and if it has public variables, properties, or methods with side effects then anything can modify its state making debugging harder

rustic ember
somber nacelle
#

i mean that really depends on your definition of "influence on performance". but in general, no- something being a singleton has no bearing on how it affects performance

solemn raven
#

Hi ,
how to check if textmeshpro has outline enabled?

rustic ember
#

How does GetComponent() work? Does it loop over all components starting with the transform, then AIC_Handler, AIC_HealthSystem, etc.?

solemn raven
rustic ember
#

I have always tried to avoid GetComponent as much as possible, only doing it once at the start, etc.

somber nacelle
#

the Find methods search the entire hierarchy, GetComponent would only search the object it is called on

rustic ember
rustic ember
#

Surely that must make it transparent

somber nacelle
rustic ember
#

Probably something to do with what game object is first in memory

#

How did you mark the text as a quote?

This is cool

somber nacelle
#

> and space before the text

upper pond
#

anyone else getting the problem where when you make a gameobject a prefab you cant assign gameobjects and scripts in the inspector? is this a bug or feature?

somber nacelle
#

assets cannot reference scene objects. prefabs are assets so they cannot reference anything in the scene, you would need to pass references when the object is instantiated

upper pond
#

thanks

lime widget
#

I want to rotate my player around an object. I did this using RotateAround but sith this function it just rotates the player and keeps the velocity to 0. How can i make it so that i can modify the velocity as well?

buoyant otter
#

Maybe someone can answer a question for me. I am learning the Input System, and followed this guide
https://medium.com/@MJQuinn/unity-handling-input-with-the-input-system-2605807fd2c6
I changed some things so the movement would be for my camera and not a player object.
I am reading on docs.unity about the input system and it refers to enabling the action moveAction.Enable()
In the guide that wasn't used and I didn't use it either yet my camera moves around just fine.
Maybe it is because I am using a PlayerInput rather than a InputAction? I have a lot more to read but this has been bothering me.

Medium

The Input System is an incredibly robust solution to handling input between multiple devices. There are a quite a few more steps to usingโ€ฆ

somber nacelle
buoyant otter
#

Ok so maybe PlayerInput does more work for me behind the scene compared to other ones

elfin tree
#

I have a cube which can be drag and dropped, I'd like to, when it' so over the platform, to kind of lock it in so it hovers and can also be dragged out. I'm considering physics for this, any ideas on what would be a good approach for this?

verbal crown
#

Any idea what on earth I am doing wrong here? Trying to make a candle script for both lit and unlit candles and turn unlit into lit so they can light other candles. But it only triggers if 2 LitCandles collide.

public class Candle : MonoBehaviour
{
    public bool isLit = false;
    public GameObject fireEffect; // Reference to the GameObject to be turned on when the candle is lit

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("LitCandle") && !collision.gameObject.GetComponent<Candle>().isLit)
        {
            Debug.Log("Candle Collide");
            collision.gameObject.GetComponent<Candle>().isLit = true;
            // Call a function on the other candle's script to trigger the fire effect
            collision.gameObject.GetComponent<Candle>().Ignite();
        }
    }

    public void Ignite()
    {
        isLit = true;
        // Turn on the fire effect GameObject if it exists
        if (fireEffect != null)
        {
            fireEffect.SetActive(true);
        }

        // Change the tag of the candle object to "LitCandle"
        gameObject.tag = "LitCandle";
    }
}
#

it won't trigger if the unlit is just tagged "Candle"

somber nacelle
#

you check if the colliding gameobject has the LitCandle tag. then if it does and if its isLit bool is true you then call Ignite on it.

verbal crown
#

so am I doing it backward? I don't understand

somber nacelle
#

you only check the colliding object then only modify the colliding object

#

so what happens if the colliding object does not have the LitCandle tag but this object does?

verbal crown
#

It only works if the colliding object is already LitCandle

#

I am trying to make it work so the same script can be on both objects

somber nacelle
#

think about it real quick, if this object is a LitCandle but the colliding object is not, which candle will be ignited?

verbal crown
#

hopefully the unlit candle and get turned into a litcandle

somber nacelle
#

well according to your logic the lit candle will be ignited

verbal crown
#

so thats why I am asking, where do I have it backward

somber nacelle
#

both

#

but also only one

solemn raven
#

hi ,
im trying to change TextMeshPro outline color value via code.
i have noticed a strange behaviour and a manual way around it .

public Color _c 
textMeshPro.outlineColor = _c;
textMeshPro.ForceMeshUpdate();

the above code alone is not working.... Untile I manually change the color on the editor, it start changing it back to _c 's value.

#

it seems that i need to do some sort of refresh to the color for it to work, and ForceMeshUpdate(); is not doing it

verbal crown
#

I am looking at it from the unlit candle side, I have if it collides with a lit candle and is NOT already lit, then run Lit true, and ignite on self.

somber nacelle
verbal crown
#

ya, the gameobject for lit is itself

somber nacelle
verbal crown
#

that was the code

#

gameobject fireEffect is the flame on itself

somber nacelle
#

then your answer should have been "no, boxfriend, i have not changed the code so that Ignite is being called on this object, i have left it being called on the colliding object"

verbal crown
#

ya, I didn't even know that was possible

somber nacelle
#

you didn't know it was possible to call an object's own methods from within that object's methods?

verbal crown
#

I would have to drag every random flame into the inspector for the gameobject

somber nacelle
#

that's not at all what i said

#

let me point out your issue again so hopefully you see what is happening:

you check that the colliding object has the LitCandle tag which has been applied by the Ignite method
if it does have that tag (and the second condition is true) you then call the Ignite method on the colliding object (the one with the LitCandle tag)

verbal crown
#

gotcha, so how do I call ignite on itself instead?

somber nacelle
#

you just call Ignite

mystic ferry
#

is [field:SerializeField] specifically for serializing properties? can't seem to find anything about it

somber nacelle
#

yes, it targets the backing field of an auto-property

mystic ferry
#

gotcha, and that's the only use case?

#

just making sure

somber nacelle
mystic ferry
#

thanks for the link

verbal crown
fathom geode
#

is there a way I can hide/prevent some variables from having default references in the inspector

solemn raven
fathom geode
#

doesn't work

#

that only works if the script is attached to a game object

solemn raven
#

is it an editor script ?

#

I believe what you are looking for is making a CustomEditor basically u need to prevent all defaults and serialize only the variables you want to show.

fathom geode
#

it's a script that other scripts reference but it doesn't live in the scene or have a game object it should be attached to
I was hoping I wouldn't need to write a custom editor specifically for that, it's my first time utilizing default references and I haven't found much or any documentation on how they are intended to be used

#

I'll try that, ty

cosmic rain
fathom geode
#

they're public and need to be but you saying that made me realize I can just make them {get; private set} and solve my problem

cosmic rain
#

Yes, don't use public fields, use properties

solemn raven
#

the problem is fixed as soon as i opened the color picker and picked any different color

#

something gets updated and fixes the problem .
I also notice the word ( instance ) appears next to the shader's property bar

#

it looks as if the game created a new instance of it , that wasnt their before I opened the color picker and changed the color

#

so far UpdateVertexData(); and ForceMeshUpdate(); does nothing

cosmic rain
frail kindle
#

Hello, my On Click () event which is connected to my onEscapeButtonClick() doesn't want to change gameIsPaused boolean to false in my code: https://hatebin.com/kihsfmqqle

cosmic rain
#

If built-in properties don't work, you could probably set the correct material property via the material reference.

solemn raven
#

Im trying to clone it on run time

cosmic rain
#

Clone what?

#

Normally setting .outlineColor should work I think. You could try setting the material property directly, as I mentioned before.

amber forge
#

im using this for my enemys to shoot, but when i use it for my enemy spawner it starts spawning like 50000 enemies in one second, thing that dont happens with enemy bullets, someone knows what happens? am having this problem since 3 days and no one have been able to help me (i pasted this on general since no one in begginer made to help me out, maybe here someone can help me)
https://pastebin.com/L5Cbhc3v

cosmic rain
#

Perhaps the issue is because yourt cloning something..?@solemn raven

cosmic rain
amber forge
swift falcon
#

Hi, I have a question. I'd like to make something like simulacra, but I can't seem to understand the logic behind the coding. Does every app I press on the phone, open a new scene? Is that how it's done? https://www.youtube.com/watch?v=ICQvVQd3gdU&t=2283s&ab_channel=Joshiball

#NoCommentary

โ‰ก Want to support the channel? You can do so by:

โ‰ก Social Network Links:

โ–ถ Play video
candid trench
#

So, i have this function that generates a mesh.
the worldHandler.world array is a 2-d array with about 40,000 entries in total inside of it.
Now, this runs kind of smooth as butter.
However, i opened my task manager and noticed that the programs memory usage is rising at a rapid pace.

Do i need to de-allocate something in this script?? I was under the impression that c# kinda does that automatically

cosmic rain
#

From your description it sounds like an issue that would require a thorough debugging. What steps did you take to figure it out?@amber forge

solemn raven
#

how to clone material the right way ?

cosmic rain
soft shard
soft shard
solemn raven
cosmic rain
frail kindle
solemn raven
cosmic rain
solemn raven
#

what the editor does is cloning the material appearntly then apply it , i wanna do the same

solemn raven
#

it just doesnt work

cosmic rain
#

What material does it use?

solemn raven
#

the default

cosmic rain
#

Ok, that could be the issue.

solemn raven
#

im talking about the outline tho

cosmic rain
#

Create a new material in the editor and assign it instead of a default one.

solemn raven
soft shard
cosmic rain
frail kindle
frail kindle
waxen burrow
#

Hey y'all, hopefully Im putting this in the correct place; I was attempting to make a procedural walking script based off a tut on youtube from filmstorm...
While the script seems to work fine, the player movement does not. Unfortunately he did not include that segment in any tutorials I could find, so I had to throw together a root animation blend to try and get something that worked. I got the animations to update correctly (at least I think), but the character fails to move. After some thinking I believe the source is the camera, as he used a third person camera system while I am attempting to use pov. This would be fine but the movement is seemingly based off the position / rotation of the camera and I'm not sure how to adapt the script to match, any Ideas?
https://hastebin.com/share/uyikitobet.csharp

solemn raven
waxen burrow
soft shard
leaden ice
#

make that based off... whatever you actually want it based off.

waxen burrow
#

so pretty much the only thing I need to do is change camera to the position of any object? and If so, would making said object tied to a point in the center of the player view mess anything up?

cosmic rain
leaden ice
#

define forward and right how you want them defined

#

You said you didn't want it to be based on the camera

#

what do you want it based on?

waxen burrow
#

sorry I meant change the var camera to any object

leaden ice
#

Oh sorry I think - yeah I misread

#

sure if you have some other object that you want to base it off

#

you can put any Transform you want there basically

waxen burrow
#

all good, I phrased it funky; thanks I'll give it a try!

leaden ice
#

for example - the player object itself

solemn raven
#

or at least that is what seem to be working

frail kindle
unreal ingot
#

I would definitely say I'm still a complete beginner, but I have what I think to be a more complex question, so I will ask it here (sorry if this doesnt belong here!) I have a material that I apply to my mesh whenever it satisfies a certain condition, but it is supposed to be merely an overlay. How would I go about "merging" two materials? (as in like, overlapping them). The material I'm overlapping is just a semi-transparent colour tint if that makes things easier, I am trying to make some gameobjects have a red transparent tint to them sometimes and a green transparent tint at other times

cosmic rain
frail kindle
soft shard
# frail kindle The only script that modifies the gameIsPaused variable is the one I sent. The M...

I dont see anything from what youve shown that looks to be incorrect, if the function is being called, and nothing else modifies the variable, I cant see a reason for it not to change, unless the value starts false, the approach I would normally take for this is using 1 function as a toggle, you may not even need the bool if your "pause menu" active state can act as what your bool would do, you could use a getter property instead if other scripts need to know about the state, for example:

public bool IsPaused {get {return pauseMenu.activeSelf;}}

public void TogglePause(bool isOn)
{
pauseMenu.SetActive(isOn);
Time.timeScale = isOn ? 0 : 1;
}

void Update()
{
if(someKey) {TogglePause(!IsPaused);}
}

Your button then could use the one TogglePause function - this is just personally how I would approach the kind of system your after, maybe easier to manage

waxen burrow
# leaden ice for example - the player object itself

unfortunately setting it to another object didn't change anything ๐Ÿ˜ฆ
I know its a bit to ask but would you or anyone who reads this be willing to look at the pastebin I linked [in original Q] just to see how the movement script is working (I have an idea but not a full picture). At this point I just want to discern if this is the fault of the script or the root transforms of the animations

lament mural
#

I'm trying to make a bit of code that'll clamp the rotation on a GO between 2 values. I thought this'd be straight forward at first as I see that in the Inspector, the rotation values start at 0 and go up past 360 and into the negatives under 0. Unfortunately, when trying to grab the EulerRotation values, it seems to reset above and below 0->360 values instead of giving me the numbers I see in the Inspector.

  1. Does anyone know how to get the same values as you can see in the inspector?
  2. Might there be a better way of clamping my rotation values keeping in mind that min/max values might go beyond the bounds of 0->360?
ashen yoke
#

@lament mural assuming the inspector angle is -15, what is the real angle?

lament mural
#

The local angle would be 345. Which is what EulerAngle gives me.

ashen yoke
#

right how would you represent a convertion between the 2?

#

using math

lament mural
#

Math? I'm not sure.

#

360 - 15?

warm fractal
#

Hey guys, I could use a hand with my UI code. I instantiate a bunch of ItemSlot prefabs, and my inventory windows are set with layout group components. Unfortunately because of the instantiation the first time they "open" an inventory in code, the layouts aren't updated and show incorrectly until the next time the windows are disabled -> enabled. I tried using LayoutRebuilder.MarkLayoutForRebuild(windowParent); on a variety of the objects, but it didn't seem to have any affect.

lament mural
warm fractal
ashen yoke
#

what inspector does is some artist friendly mumbo jumbo, probably uses quaternions to store the user rotation which allows it to display those -720 pop shove it

lament mural
ashen yoke
#

nah im being dumb i used -90/90 clamp a lot, its useful

lament mural
ashen yoke
#
        public static float ClampAngle(float angle, float min, float max)
        {
            if (angle < -360F)
                angle += 360F;
            if (angle > 360F)
                angle -= 360F;
            return Mathf.Clamp(angle, min, max);
        }
warm fractal
lament mural
ashen yoke
#

there was a method to force rebuild layout

lament mural
#

This would probably be better.

warm fractal
ashen yoke
#

try

            RectTransform tr;
            tr.ForceUpdateRectTransforms();
warm fractal
#

Ho, will do

#

Not working.

ashen yoke
#

used on content root?

warm fractal
#

I've used it on it's parent, it's parent's parent, on the "window" parent...

ashen yoke
#

trying to remember how i did it

warm fractal
#

Whats frustrating is that it looks right after the window "closes" and "opens" again.

#

So clearly everything is setup to look properly, but it doesn't update somehow.

lament mural
ashen yoke
#

@warm fractal im digging through the sources

#
            CanvasUpdateRegistry.instance
                .GetType()
                .GetMethod("PerformUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                .Invoke(CanvasUpdateRegistry.instance, null);
#

came up with this, testing it myself

#

you can test as well

warm fractal
#

Didn't work, but I've got another trick or two up my sleeve to try.

ashen yoke
#

you set the layout dirty before calling it?

#

any errors?

#

have to first LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform)

warm fractal
#

Trying

#

Nope.

ashen yoke
#

it adds the hierarchy to a queue, then updates when its procd, directly invoking that method should in theory force an update

#

hm

warm fractal
#

I'm actually rather amused by the lack of these working. Does it work for you?

swift falcon
#

Can someone help, please? I did this to my canvas, but my objects inside the canvas are still showing

frail kindle
# soft shard I dont see anything from what youve shown that looks to be incorrect, if the fun...

Sorry for the late reply, I decided to try following a tutorial and it somehow worked even though the code looks practically the same to what I was writing: https://hatebin.com/hflgpqazol
Also I put the entire PauseMenu Canvas under like a big GameController Empty and I put the PauseMenu Script into the Empty and it works perfectly fine. Here is how the hierarchy for the Canvas looks like now if you're curious. Thank you for helping me out though.

ashen yoke
warm fractal
ashen yoke
#

non programming question

warm fractal
#

Might it do with the game objects being inactive before/after running the code? Survey says: no.

#
            LayoutRebuilder.MarkLayoutForRebuild(window);
            window.ForceUpdateRectTransforms();
            CanvasUpdateRegistry.instance
                .GetType()
                .GetMethod("PerformUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                .Invoke(CanvasUpdateRegistry.instance, null);```
#

Like, idk man, I feel like something here would've caused a change, y'know?

ashen yoke
#

the window itself contains the layout?

warm fractal
#

I'm still testing on each individual GameObject up the hierarchy to test.

#

So...Yes.

ashen yoke
#

see it traverses up

#

i dont see anything preventing registration in queue

warm fractal
#

Well I've managed to find out maybe a fraction of a solution

warm fractal
# warm fractal ``` window.gameObject.SetActive(true); LayoutRebuilder.Ma...

In addition to this code, I'm also running window.gameObject.SetActive(!window.gameObject.activeSelf); twice in a row, and that seems to work for one of the inventory windows. I'm currently experimenting with it, but recompiling every time after a single line of code changed is taking me a bit to figure out.

ashen yoke
#

ah right

#

i think i found it

warm fractal
#

Oh?

ashen yoke
#

Canvas.ForceUpdateCanvases();

#

its static

warm fractal
#

Probably should've mentioned I had it in there too

ashen yoke
#

damn

warm fractal
#

I haven't read the whole forum but since I've come across this haphazard solution I was going to further look into it and experiment. Guess I'll try reading the rest of it tho

ashen yoke
#

canvas is a blackbox btw

warm fractal
ashen yoke
#

means the c# class is just a wrapper around native one

#
        [FreeFunction("UI::GetETC1SupportedCanvasMaterial")]
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern Material GetETC1SupportedCanvasMaterial();

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal extern void UpdateCanvasRectTransform(bool alignWithCamera);
#

example from canvas

#

so all its internals are hidden in native code

warm fractal
#

I have never even seen the keywords "internal" or "extern" before

#

Never had a "formal" training on C# either, ig.

ashen yoke
#

same

warm fractal
#

Showoff, lol

ashen yoke
#

tho ForceUpdateCanvases() just calls willRenderCanvases event

#

which is fed delegates you make with MarkLayoutForRebuild(window);

#

it should work haha why isnt it

#

missing something

warm fractal
#

Thats the million dollar question, now isn't it?

#

Probably to do with my hierarchy, I'm willing to bet.

#

Time to try a bunch of things with new layouts.

#

The forum post I linked has a user mentioning it being something about the ContentSizeFitter refreshing before/after the parent does, leading to things not updating properly.

ashen yoke
#

what if you do WaitForEndOfFrame, then call ForceUpdateCanvases multiple times

#

nah that would clear the "dirty" state on first call

#

meaning youd have to set the whole thing dirty between calls

#

assuming the issue is circular dependency like you said

carmine field
molten thicket
#

Hi guys,

I'm stuck trying to convert downloaded scores into an integer array. The situation is simple, I'm downloading the following numbers from my table:

20, 7, 2, 23

string RawData = Encoding.UTF8.GetString(www.downloadHandler.data);

I then split them up:

[] Data = RawData.Split(' ');

I then convert them into an integer array:

int[] Score = Array.ConvertAll(Data, int.Parse);

Now normally this works when you manually create an array and populate it with string values and then convert it. however for some reason Unity yells at me and says that my Input string was not in a correct format.

The end goal is simply sort the data from highest to lowest - If there is a better way of doing this, I'm all ears!

Any help would be greatly appreciated!

lime widget
#

I want to rotate my player around an object. I did this using RotateAround but sith this function it just rotates the player and keeps the velocity to 0. How can i make it so that i can modify the velocity as well?

molten thicket
#

Hi guys

toxic notch
#

Isn't lerp used for arriving at a point over a certain time? How would that help in a calculation?

quartz folio
cosmic rain
#

The heck is going on with discord here..?๐Ÿ˜–

quartz folio
#

Nothing seems wrong on my end, but discord is quite bugged on mobile for me

cosmic rain
#

Ah, that must be the issue.

toxic notch
#

What am I lerping the rotation and magnitude to?

ashen yoke
granite nimbus
#

what is big O for Mesh.SetVertices, Mesh.SetIndices, and Mesh.SetUVs?
also Mesh.RecalculateBounds, Mesh.RecalculateTangents and Mesh.RecalculateNormals?

#

and in general, are there publicly available performance tests for Unity api?

real anvil
#

Calculating bounds can definitely be done in O(n)

#

The Set functions allocate some memory, copy your stuff to that memory then upload it to the GPU when needed

granite nimbus
clear tiger
#

One message removed from a suspended account.

severe marsh
clear tiger
#

One message removed from a suspended account.

bronze crystal
#

How can i manage different game states? Like winner -> stage 2 -> generating new level -> spawning monsters etc...

soft shard
wide pine
#
private bool spoke = false;
private bool speaking = false;

 private IEnumerator PlayDialogue(int dialogueNumber)
    {
        speaking = true;

        DialogueSource.clip = DIALOGUE[dialogueNumber];
        DialogueSource.Play();

        yield return new WaitForSeconds(DialogueSource.clip.length);

        spoke = true;
        speaking = false;
    }
if (Input.GetKeyDown(KeyCode.E))
                    {
                        dialogueNumber++;
                        NextDialogue.Play();
                        spoke = false;
                        StopCoroutine(PlayDialogue(dialogueNumber));
                    }``` Hey guys StopCoroutine() isnt stopping my PlayDialogue Coroutine, can I have some help please?
wide pine
#

thanks i already fixed it but will keep this is mind

bronze crystal
#

I have my check game state function: ``` private void CheckGameState()
{
// Check the current game state and update the game accordingly
switch (currentState)
{
case GameState.MainMenu:
// Handle the main menu state
// Go to the main menu scene

            break;

        case GameState.InGame:
            // Handle the in-game state
            // Go to the start game scene

            break;

        case GameState.Paused:
            // Handle the paused state
            // Show game paused UI

            break;

        case GameState.GameOver:
            // Handle the game over state
            // Show game over UI

            break;
    }
}```
#

but how do i trigger this with my start button in my mainmenu

vagrant blade
#

Call the function on the button OnClick event from the inspector?

#

Your function will need to be public for it to be accessible.

craggy cedar
#

What is a controlID for Handles?

wary wagon
#

How can i make a Character Controller push another one when there is a collision ?

#

I want my monsters to simply not be stacked in a single pixel but round around the player

bronze crystal
sweet inlet
#

Hope someone can give me q quick hand with my problem, i got a folder outside my program where i want to load images from, the part which makes this difficult is that the user should be able to put any png image inside that folder and it should work, all solutions i found so far require to give a filename, which isnt an option in my case

bronze crystal
#

How do i properly say this? private void TriggerPause() { // if instate game is ingame if (GameState.InGame) { if (Input.GetKeyDown(KeyCode.Escape)) { GameState.Paused; } } }

leaden ice
#

Right now you basically have cs if (5) { 3; }

bronze crystal
#

yes i used this code in gamemanager but switched it over now to gamecontroller

#

its better

leaden ice
#

You need to use your variable

bronze crystal
#

but

#
    {
        // if instate game is ingame
        if (currentState.InGame)
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                GameState.Paused;
            }
        }
    }```
#

i get error

leaden ice
#

Because... wat???

bronze crystal
#

error CS0176: Member 'GameManager.GameState.InGame' cannot be accessed with an instance reference; qualify it with a type name instead

leaden ice
#

== to compare things

#

= to assign things

#

You will need to use these tools ๐Ÿ™

bronze crystal
#

what was the shortcut in visual studio, to change the name of variables on all places.

buoyant crane
soft shard
soft shard
# sweet inlet Hope someone can give me q quick hand with my problem, i got a folder outside my...

You could use System.IO.Directory.GetFiles: https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=net-8.0 and search for "*.png" as your pattern, that should then give you an array of file paths in that folder whos extension ends with .png, you can then loop through that and do what you need with the file data, if your planning on using this for some kind of "image import" feature, like applying a user texture on something, theres a good chance youll already know the exact image the user wants to use, since they would need some way to "select" that image to be imported anyway

sweet inlet
#

i'll have a look, thanks

hybrid goblet
#

not sure which channelt to put this in, Imma just use this one

can unity work with LF file endings?
I finally uploaded my project to git and it said the CRLF fileneding will be replaced by the LF ending, theoratically it has to work just fine, since it is just replacing 0x0D0A with 0x0A, but the qeustion is, if unity supports it

bronze crystal
#

i have like a little problem

soft shard
# wary wagon I want my monsters to simply not be stacked in a single pixel but round around t...

Im not sure if just adding a force on collision will solve your problem on its own, it may just make predictable "lines" of your enemies, unless you have very few to begin with - I think what you might be looking for is "AI flocking" or "AI swarming" algorithms, or possibly "object avoidance" using the player and other AI as objects to move close-to but not within the same space the player or others occupy, im not too experienced with implementing those algorithms, though it may be worth looking into, depending on how complex your AI logic is, and how many you may be working with

bronze crystal
#

i have like my gamestate switch in update to check games states, but it also game updating. ``` void Update()
{
CheckGameState();
TriggerPause();
}

public void CheckGameState()
{
    // Check the current game state and update the game accordingly
    switch (currentState)
    {
        case GameState.MainMenu:
            // Handle the main menu state
            // Go to the main menu scene
soft shard
bronze crystal
#

well checkgamestate has to be in update to continuously see which state the game is in.

#

but i think it triggers so much because i have change scenes yet so it keeps hanging ofcourse

soft shard
# bronze crystal well checkgamestate has to be in update to continuously see which state the game...

Well how often does your game state change? Wouldnt it only change if something specific happens in the scene? For example, only if the player dies, then the game might change states to a "game over" state, or only if the player hits some end-trigger the game state might change to a "level complete" state? Or are these states something that can change often and not always on something specific happening?

bronze crystal
#

yes ofcourse

#

but how would the code see that by keep it in update or not?

soft shard
# bronze crystal but how would the code see that by keep it in update or not?

Well what im suggesting is you shouldnt need Update at all, since once a state changes, it likely is going to stay the exact same until some event causes it to change again, so you could setup an event with a property (or function if you prefer) and have things subscribe to thatt event to know when it changes, then keep a static reference of the change, essentially doing the same job as checking in Update every frame, except now its not an "every frame" check just "when x needs to know" check

bronze crystal
#

oke thats new to me

soft shard
# bronze crystal oke thats new to me

If it helps, heres an example of how I might implement it:

public class SomeGameStateSingleton
{
public static System.Action<GameStateEnum> onStateChanged;

public static GameStateEnum State {get {return currentState;} set {currentState = value; onStateChanged?.Invoke(currentState);}}
static GameStateEnum currentState;
}

public class SomeStateChangeScenario : Mono
{
void OnCollisionEnter(...) {SomeGameStateSingleton.State = changedToState == GameStateEnum.GameOver;}
}

public class SomeSpecificScript : Mono
{
void Start()
{
SomeGameStateSingleton.onStateChanged += DoSomething;
}

void OnDestroy()
{
SomeGameStateSingleton.onStateChanged -= DoSomething; //always unsubscribe at the end of the objects lifespan or use OnEnable/OnDisable instead of Start/Awake and OnDestroy
}

void DoSomething(GameStateEnum changedToState)
{
Debug.Log("state is now: " + changedToState);
if(changedToState == GameStateEnum.GameOver) {...}
}
}

There are other ways you could implement something like this, but this would be the general idea - either a property or a function that lets you change the state, call an event when it changes, subscribe things to the change of the event, if its to a state that thing cares about, perform relevant logic, since the state in this example will stay "GameOver" until something else decides to change it, you dont need Update to check the state, if something needs the current state, it can just check the value of SomeGameStateSingleton.State, or set it to cause a change

bronze crystal
#

i mean like i do have a enem

#

enum

soft shard
# bronze crystal i mean like i do have a enem

Right, and you can keep your enum, in fact this example is under the assumption that your enum logic would be the same as it is now, its just moving checks from having to be done in Update to cover everything, to each thing that actually cares about a specific state to listen for when its relevant, and having game logic (like colliding in a damage zone or enemy killing a player etc), update the state once, which in turn, notifies the code that cares (such as maybe your UI needing to know when the game ends) - in the same example, if the state was say "LoadingLevel", the UI may still be notified, but since the state isnt "GameOver" itll just skip over the code unless you also specifically check for "LoadlingLevel" and "GameOver", if your UI cares about both

bronze crystal
#

hmm

#

just a litte bit intermediate, so gotta check it out.

prisma birch
#

I'm trying to add a component using a string, from some reading, it should work using Type.GetType() but I'm having trouble getting this to not return null. Any ideas? Here's my code:

  {
    string scriptName = e.stateMachineData.states[i].script.name;
    Type type = Type.GetType(scriptName);
    e.references[i].script = (EnemyState)statesObject.AddComponent(type);
  }
#

I tried even using other types like MeshFilter instead of my custom script and it's still not working :/

soft shard
# bronze crystal just a litte bit intermediate, so gotta check it out.

I would say you could maybe make a second script and try out the example above, to see if it is what your looking for, it may take a bit to understand it without having an implementation infront of you to see how changing the state affects the things that care about the change - this whole approach is similar to a "messaging" or "observable" pattern if you wanted to find more examples online as well

dense edge
#

how do i get the gameobejct that ws dragged in a drag and drop event?

#

i need to get soem data from a dragegd obejct, but the event of drop is on the slot

#

how do i do it?

subtle herald
#

It's got 2 classes there.... so I'm gonna assume no. Lol

bronze crystal
#

i see like 3

subtle herald
#

Yeah lol I missed one

soft shard
# bronze crystal is this all like 1 class?

Its multiple classes, SomeGameStateSingleton would be similar to what you have, just as a singleton, SomeSpecificScript would be whatever scripts care about a state change or need to perform logic based on a certain state, and SomeStateChangeScenario is whatever causes a state change in your game logic

subtle herald
#

Why ask if it's all one if you know it's not? ๐Ÿ˜‚

bronze crystal
#

it was a little bit confusing

soft shard
#

Tbf, its typed entirely on Discord, so very poor formatting

bronze crystal
#

you could always use hatebin

#

but basically this code: ```using UnityEngine;

public class GameManager : MonoBehaviour
{
public enum GameState
{
MainMenu,
InGame,
StartGame,
Winner,
NextLevel,
MonsterSpawn,
Paused,
GameOver,
QuitGame
}
}```

#

i exchange for the first class singleton?

soft shard
#

Essentially, yeah, though you can keep your enum as-is, youd just be expanding that class

bronze crystal
#

encountering a litte problem, because in the new scene i dont have the game manager object with the script, and when i do put it in i goes back to mainmenu state.

#

so how do you track everything across all scenes.

soft shard
# bronze crystal so how do you track everything across all scenes.

This is what a singleton helps with, although in my example, theres no need to use Update or any Unity specific functions, so it can just be a global class without needing to use MonoBehaviour - if you prefer it to be a part of the scene, youd have to use DontDestroyOnLoad and treat it as a scene-level singleton, ensuring that theres only ever 1 copy of the object/script in the scene at any given time

prisma birch
leaden ice
#

what type of variable is script here?

#

Are you sure you don't want:

Type t = e.stateMachineData.states[i].script.GetType();
statesObject.AddComponent(t);```?
woeful bramble
#

Does GetComponentInParent<T>() allocate garbage? If you have a source for your answer, would appreciate it - ty!

leaden ice
#

Also it seems like you already know the type of the script will be EnemyState right?
So why not just
statesObject.AddComponent<EnemyState>()

prisma birch
# leaden ice what type of variable is `script` here?

It's one of my enemy state machine states. They are a child class of a state called EnemyState which is a Monobehaviour. Thought maybe since it is a derived class it could cause issue but I tested with some default classes like MeshFilter and SphereCollider with the same issues.

leaden ice
#

that gives you the name of the GameObject it's attached to

prisma birch
#

which is why I'm using the string

bronze crystal
#

@soft shard trying to implement to second class, but i get error: ``` private GameState currentState;
private GameState changedToState;

void Start()
{
    // Set the initial game state
    // currentState = GameState.MainMenu;
    GameManager.State = changedToState == GameState.MainMenu;
}

error CS0117: 'GameManager' does not contain a definition for 'State'```

leaden ice
#

you can't reference script assets at runtime except as a TextAsset

#

since MonoScript is editor-only

prisma birch
leaden ice
#

So those are MonoScript fields?

prisma birch
#

This is a scriptable object that houses all of my state machine states, I want to add each of the state scripts

leaden ice
prisma birch
#

They're UnityEngine.Object fields, maybe that's where I'm wrong

leaden ice
#

you can't actually do things this way

#

but

#

MonoScript is editor-only

soft shard
leaden ice
prisma birch
#

This is an editor script

leaden ice
#

ok if it's an editor script then

#

MonoScript is the way to go

#

which you can use in AddComponent

prisma birch
#

Sweet let me try it, thank you. I was having a hard time figuring out how to store a class using an asset rather than an instance. Object was the only thing I could find.

bronze crystal
prisma birch
soft shard
bronze crystal
#

but what are we doing here then? GameManager.State = GameState.MainMenu;

#

arent we directly changing it?

#

or do i use this private variable? ```public class GameController : MonoBehaviour
{
private GameState currentState;

leaden ice
#

GameManager or GameController pick one ๐Ÿ˜ฌ

#

Show more of your code hard to say what's going on without seeing it

bronze crystal
#

here are my two class

leaden ice
#

delete this variable in GameController

#

You don't want two variables that mean the same thing

#

Let GameManager be the source of truth, and the sole place where you store that information

bronze crystal
#

oke

#

static means availbe to all classes?

#

?

soft shard
# bronze crystal arent we directly changing it?

Yes you are directly changing it, thats actually the benifit of having it a property in GameManager, when you set it equal to something different, it fires the onStateChanged event, so if something should change the state, it should just need to call GameManager.State = ... in your case

bronze crystal
#

so in game controller i can now remove checkgamestate function in update

leaden ice
#

it's just you should be reading the state from game manager directly

bronze crystal
#

i thought the whole implementation of this, is that i dont have to check in update?

leaden ice
#

the only way around that is if you used a coroutine

#

which would probably be more complicated

soft shard
#

You can keep it, but since GameManager.State fires an event for when it changes, and you can have classes subscribe to that change, I dont think youd need Update - you can still use it if you want for some cases, but I dont think you have to

bronze crystal
#

i will check if it keeps update

leaden ice
#

Most state machines have:

  • on state enter
  • update inside the state
  • on stat exit
#

and possibly other things

#

you will still need update to allow your states to have a per-frame behavior

soft shard
#

Oh, is GameState a class all your states will be using, or a enum parts of your game checks for?

bronze crystal
#

enum parts

#

in game controller in my switch i will write what will happens once the state triggers

elfin tree
#

Hey, so I have this code that seems like it should work but does not..

  1. Removing the code in OnCollisionEnter makes it so no object can enter the barrier ever.
  2. With the code in OnCollisionEnter, the Debug.Logs work properly, it says "Trying to ingore collsion" if the object is allowed, and also allows it, and says "Collision should be blocked" otherwise but it's not colliding (not being blocked by the barrier).
  3. When the allowed object enters, the BoxController is no longer a trigger and it becomes one again when it leaves (which is the intended behaviour).
  4. DisableBarrier is not called before the issue happens.

What am I missing? RESOLVED

bronze crystal
#

I'm still dealing with some problem.

#

as you can see when i click on start button i go to the new scene and in my hierachy everything is empty, how do i transition the state to the new scene

#

i cant put game controller in there because then everything reloads and it will say, state = gamemenu again.

rustic ember
#

Just now my Visual Studio Community stopped working with Unity. I think it was when I renamed the folder containing the scripts

#

A few of the scripts I have open still look fine

#

The ones that look bad have this "Miscellanuous Files" thing instead of Assembly-CSharp

hard sparrow
#

I'm doing Mathf.CeilToInt(myInt/otherInt) and it's complaining about 'possible loss of fraction.' Isn't that the point, or...?

rustic ember
hard sparrow
#

anytime you do calculation with two ints, it will give an int?

rustic ember
hard sparrow
#

weird

gray thunder
#

Its math?

soft shard
# bronze crystal as you can see when i click on start button i go to the new scene and in my hier...

That looks like the scene is collapsed, and looks like it has loaded correctly, youd have to expand it with the arrow on the left of the scene name to see the hierarchy - though if your using a mono behavior, then you could use Awake and turn your script into a singleton, there are other ways of doing this, but more-or-less similar:

public class SomeClass : Mono
{
public static SomeClass Instance { get; set; }

void Awake()
{
if(Instance != null && Instance != this) {Destroy(gameObject);}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}

SomeClass.Instance is now how that class can be accessed, but I think you could have your state in a non-mono class to begin with and just access it in the same way

soft shard
rustic ember
soft shard
# rustic ember Thank you. Is this button safe to click?

Regenerating your project files will add all the assemblys checked above (in your case, embedded packages and local packges only), so it may add more .sln files to your root project directory (outside Assets folder), and cause VS to update if its open

soft shard
bronze crystal
soft shard
rustic ember
soft shard
#

Np

stark swift
#

Hey guys, Does anyone know how I can read the processor values in code for the new input system?

bronze crystal
soft shard
rustic ember
#

Does Unity compile to use 32-bit pointers or 64-bit?

bronze crystal
rustic ember
#

I can't find anything about it in the docs

leaden ice
#

it can do both

leaden ice
soft shard
rustic ember
vagrant agate
#

So maybe someone can point me in the right direction to tackle this.
Big circle (Parent Object) can Rotate both directions.
Little Circles (Direct Children to Big Circle)

what I want to happen is, the little circles to shoot out the direction of the arrows like the picture(my arrows suck but It just needs the same spacing in a circle around the parent object) regardless of the parent Z rotation.

I suck at angles but curious if there is some nice function that can get me on track to figuring this out.

bronze crystal
mental rover
vagrant agate
mental rover
#

along the vector from the center to the child I imagine

vagrant agate
#

so get the global center position of the parent then transform point of the child local position and draw a line out ?

mental rover
#

no, local position

vagrant agate
#

ok i c, to the children, vector 2 zero is center even in local space

mental rover
#

in that case if the center of the parent is 0,0 then you could even directly use a scale factor, e.g put child.localPosition += child.localPosition * Time.deltaTime; into update and see what happens

vagrant agate
tawny mountain
#

How can I call this rcp only on the device the player is on?

[ServerRpc]
    public void PlayerSpawnServerRpc()
    {
        TriviaGameManager.instance.playerCount.Value++;

        if (AuthenticationManager.instance.isFbLoggedIn)
        {
            networkedPlayerNameText.text = AuthenticationManager.instance.playerUserName + $" Player: {TriviaGameManager.instance.playerCount.Value}";
        }
        else
        {
            networkedPlayerNameText.text = $"Not Logged In With Fb Player: {TriviaGameManager.instance.playerCount.Value}";
        }
    }

I call it on 2 devices but the player name only shows twice on the hosting device

#

I've tried using If ( isLocalPlayer )

leaden ice
#

am I misunderstanding what you mean?

tawny mountain
#

like isLocalPlayer.. the player for this machine/device

leaden ice
#

it's unclear to me:

  • what triggers this code
  • on which machine it is triggered
  • where you want the code to run
  • what effect want it to have on which machine
tawny mountain
leaden ice
#

The server?
Some other client?
The client whose player object was just spawned?
All of the above?

#

Start is going to run on that object on all of those unless you do something to control it

tawny mountain
#

I'll provide a screenshot of whats happening

trim schooner
#

Don't crosspost. You were given the answer in the beginner channel (where this question belongs).

runic bear
trim schooner
#

Give up game development then

grizzled venture
#

It means that there is some memory that hasn't been disposed of by the garbage collector on domain reload. A domain reload typically happens when you enter play mode or recompile code. Did you find a solution to the problem yet?

cerulean oak
#

if I have a component field that isnt visualizable in the editor (a custom object) and I set it using an editor script, does it get stored and serialized?

#

or do I need to maketi a scriptableObject

torn maple
cerulean oak
#

wym

#

you can totally serialize a custom class marking it as [Serializable]

torn maple
#

Then I am not sure I understood the issue that you are having

cerulean oak
#

I want to know if its possible to do it when the field is hidden

#

from the inspector

#

in a gameobject

torn maple
#

Ah, I've never done that, but if you are ussing HideInInspector tag it should

clear tiger
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

simple egret
#

One's at Z -10, not the other

clear tiger
#

One message removed from a suspended account.

simple egret
#

Yeah, if your camera is on Z -10, it's at the same level

#

Won't be visible

clear tiger
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

tepid jewel
#

Hey! I have a plane mesh and I am trying to figure out how to extrude it. Can someone please help me? this is my mesh and I have tried to use MeshExtrusion.cs but I am getting an error.

Error:

IndexOutOfRangeException: Index was outside the bounds of the array.
MeshExtrusion.ExtrudeMesh (UnityEngine.Mesh srcMesh, UnityEngine.Mesh extrudedMesh, UnityEngine.Matrix4x4[] extrusion, MeshExtrusion+Edge[]
molten sandal
#

Hi there people, I need help with a script, a smooth camera follow script, I've seen many examples, but all of them are pretty much the same, the camera follows a vehicle

#

The problem I am having is that this ship moves really fast 800km/h+

#

And the faster it moves, the farther the camera gets away from the vehicle

#

I've been struggling to find a way to adjust the smooth time based on the velocity of the ship

#

This to prevent the camera going too far away at higher velocities

severe marsh
molten sandal
#

Thanks of the advice

#

I've been struggling with this for days

#

I think I am going to take a different approach

#

I am going to parent the camera to the ship and the offset the position and rotation baes on the speed

#

That way I could do some shaking effect as well

glossy basin
#

Hello there, this may be a beginner question, but how do I convert from Vector2[] to float2[]? I need to get the UV from a sprite texture but it only returns Vector2[]

rain minnow
lusty seal
#

are there any way create asset bundles just include the item you want so i don't have to build the entire scene into the bundle becase i'm getting an erro that not sure how to solve.
here is my client class

using FishNet;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Shiryu.Saikin
{
    public class ClientServerManager : MonoBehaviour
    {
#if SAIKIN_GAME_SERVER
        [SerializeField] private bool autoStartServer = true;
        [SerializeField] private bool useSteamworks = false;
#endif
        [SerializeField] private int attemptAmount = 1;
        [SerializeField] private GameObject retryPanelGO;
        [SerializeField] private TextMeshProUGUI retryPanelTMP;
        [SerializeField] private Button retryPanelButton;


        private void Start()
        {
#if SAIKIN_GAME_SERVER
            if(autoStartServer) InstanceFinder.ServerManager.StartConnection();
            if (useSteamworks)
                GetComponentInChildren<SteamManager>(true).gameObject.SetActive(true);
#else
            GetComponentInChildren<SteamManager>(true).gameObject.SetActive(true);
#endif
            StartCoroutine(StartClient());

        }

        public void RetryConnect()
        {
            HideRetryUI();
            attemptAmount = 1;
            StartCoroutine(StartClient());
            ShowConnectingUI();
        }

        private IEnumerator StartClient()
        {
            InstanceFinder.ClientManager.StartConnection();
            yield return new WaitForSeconds(3);
            if (!InstanceFinder.ClientManager.Connection.IsValid)
            {
                attemptAmount++;
                if (attemptAmount < 4)
                    StartCoroutine(StartClient());
                ShowRetryUI();
            }
        }

        private void ShowRetryUI()
        {
            if (retryPanelTMP) retryPanelTMP.text = "We have attempted to connect to the server 3 times and was unalbe to get a connection. you can click the retry button below to try the connection again.";
            if (retryPanelGO) retryPanelGO.SetActive(true);
            if (retryPanelButton) retryPanelButton.gameObject.SetActive(true);
        }
        private void HideRetryUI()
        {
            if (retryPanelGO) retryPanelGO.SetActive(false);
            if (retryPanelButton) retryPanelButton.gameObject.SetActive(false);
            if (retryPanelTMP) retryPanelTMP.text = string.Empty;
        }
        private void ShowConnectingUI()
        {
            if (retryPanelTMP) retryPanelTMP.text = "Please Wait, Connectiong...";
            if (retryPanelGO) retryPanelGO.SetActive(true);
            if (retryPanelButton) retryPanelButton.gameObject.SetActive(false);
        }
    }
}
hybrid quarry
#

Can anyone see why my object is not being destroyed when I roll into it? Works fine on other objects

polar marten
polar marten
empty crystal
#

Hey guys, I'm having a bit of trouble getting my raycast to follow the game object's rotation. Does anyone know how to solve this? Here's my code

polar marten
#

you should be using cinemachine, which deals with all of this

empty crystal
polar marten
#

do you see why that makes sense?

empty crystal
#

Ah ok, thanks!

polar marten
#

i don't remember the api

#

look at whatever the constructor is for Ray carefully

#

and use transform.forward as the direction

#

don't make a node editor

#

they already exist, many

#

i have never had an issue with ??

simple egret
#

It won't work reliably with anything deriving from UnityEngine.Object

#

Because it doesn't account for the "destroyed, but not null yet" state of objects, unlike when you use == or !=

cerulean oak
#

is there a json lib in unity or C# that allows me to create json objects dynamically?

#

so id do something like
JsonObject obj = new JsonObject();
obj.SetInt("intField", 5);
obj.ToString();

#

ok nvm that doesnt work for me

#

aagggg

#

I need a generic Memento object

#

where I can save ints, strings, AnimationCurves

#

guess I need to make it

ionic adder
leaden ice
arctic marsh
#

Hello everyone.

I have an object that is persistent between levels via. DontDestroyOnLoad. How can I access its contents outside of its original level? Seeing as I just simply drag in the object from the Hierachy.

cerulean oak
leaden ice
#

(note that JObject from Newtonsoft will indeed do what you originally asked for)

leaden ice
arctic marsh
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
    public List<Inventory_BaseClass> inventorySlots;
    private static Inventory inventoryInstance;
    // Start is called before the first frame update
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
        
        if (inventoryInstance == null)
        {
            inventoryInstance = this;
        }
        else
        {
            Object.Destroy(gameObject);
        }

    }
}
leaden ice
#

e.g.

public static Inventory Instance => inventoryInstance;```
#

that's all

arctic marsh
#

Nope, thats just another way to set its access.

leaden ice
#

you can access this property from anywhere

#

by typing Inventory.Instance

cerulean oak
arctic marsh
#

Ah, okay, that makes sense.

leaden ice
#

either way you're going to have to write stuff for each one

cerulean oak
#

Yeah

#

I don't really know if I can create a class tho, because I need to store it in a class without knowing what it is

#

I think that shouldn't be a problem tho

#

Idk

leaden ice
#

I don't get what you mean

cerulean oak
#

I have done this before but not in unity

leaden ice
#

If you "don't know what it is" wouldn't you have that same problem with JObject too?

#

what's the use case here?

cerulean oak
#

I have the superclass

#

And I serialize the type

#

To instantiate it

leaden ice
#

Ok so you have polymorphism

#

and you aren't sure how to handle deserializing into subclasses

#

when you have a List<ParentClass>

#

something like that?

arctic marsh
#

Okay, so if I understand correctly. This goes in the global script.

    public static Inventory inventoryInstance;

And this goes in the script I want to reference it?

    public Inventory = Inventory.Instance;

Doesn't quite seem to work.

velvet quartz
#

How can you break the current Update loop when you aren't on update but on a function ?

leaden ice
leaden ice
#

you don't need this at all, delete it:
public Inventory = Inventory.Instance;

leaden ice
#

just type Inventory.Instance directly whenever you want to use it @arctic marsh

leaden ice
# velvet quartz how you do that
bool MyFunc() {
  if (something) return true;

  return false;
}
void Update() {
  bool shouldStop = MyFunc();
  if (shouldStop) return;
}```
velvet quartz
leaden ice
#

"each function"?

velvet quartz
#

if (shouldStop) return;

#

each function you call on your update loop

leaden ice
#

you put it anywhere you want to conditionally stop running Update

velvet quartz
#

ok bc i need to stop for a frame when i enable disable nav mesh agent obstacle

arctic marsh
leaden ice
#

you have to show me what you tried

cerulean oak
#

Well

#

I have the type serialized fine

#

But the fields are the problem

arctic marsh
#

Yep. I was.
Alright, thank you @leaden ice , this makes quite a lot of sense.

#

I get a nullpointer error for doing this in engine.

    public List<Inventory_BaseClass> inventory;
    // Start is called before the first frame update
    void Start()
    {
        inventory = Inventory.Instance.inventorySlots;
    }

Obviously this is because nothing exists yet, it wont do until the games first loaded.

#

Can I suppress this error or should I do something else?

simple egret
#

You should assign Inventory.Instance in Awake

#

Awake: initialize yourself
Start: get references from other scripts

leaden ice
#

generally the point of the singleton inventory is to have one centralized place to access it

arctic marsh
# leaden ice why are you doing this

Ok, let me explain my end goal.

I have a pickup system, I add these items to a List in an Inventory object that persists throughout all levels.

This script, I want to get all of that data and add it to a UI display.

#

the UI display is in a different scene entirely though

arctic marsh
#

Right, which is what I thought I was doing, I wasn't ignoring you. Again I'm just trying to access that information now.

leaden ice
#

Well obviously yes the inventory needs to exist before you access it

arctic marsh
#

Yep.

#

Which is why it probably throws the error in editor, but would probably work fine in a build.

#

Can't hurt to try, but I'd need to suppress that error somehow.

thick socket
#

Is there a way to do IAP only through code? Everything I find requires an IAP button which I cant use for design reasons

oblique spoke
thick socket
#

Ill certainly try and look into that

#

From what I was seeing it took like a function to execute when successful

arctic marsh
#

the object doesn't even seem to recognize that its not meant to destroy itself on load, do variables within these objects get reset also?

oblique spoke
arctic marsh
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
    public List<Inventory_BaseClass> inventorySlots;
    public static Inventory inventoryInstance;
    public static Inventory Instance => inventoryInstance;
    // Start is called before the first frame update
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
        
        if (inventoryInstance == null)
        {
            inventoryInstance = this;

        }
        else
        {
            Object.Destroy(gameObject);
        }

    }
}
thick socket
oblique spoke
thick socket
#

Thanks!

#

@oblique spoke is there a way to create Products for the IAP Catalog through code also?

molten thicket
#

Hey guys!

I'm experiencing a whack issue;

I have two integers, the static will update, but the local integer stays on 0 even if I increment it. ๐Ÿคฃ ๐Ÿ˜ญ

Any idea why this might be the case?

oblique spoke
solemn star
#

I am fed-up with the bug of scroll wheel. Since I am using laptop and obviously there is no scroll wheel in laptop and so when I use scroll wheel it in my unity code for zoom it either return 0 or returns the delta moved and moves my camera accordingly

void HandleZoom() {
        // Get the distance between the camera and the target object
        float distance = Vector3.Distance(transform.position, transform.position);

        // Calculate the new field of view based on the distance
        float fov = Mathf.Lerp(maxZoom, minZoom, distance / 100.0f);

        // Set the camera's field of view
        cinemachineCam.m_Lens.FieldOfView= fov;

        // Zoom in/out using the mouse scroll wheel
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        transform.position += transform.forward * scroll * zoomSpeed;
}
#

currently it has no action on the usual way we use scrolling on touchpad

#

it is reflecting the change in position of my camera when I move my cursor

spiral ibex
#

float distance = Vector3.Distance(transform.position, transform.position);
that line doesn't seem right

solemn star
solemn star
# spiral ibex ` float distance = Vector3.Distance(transform.position, transform.positio...
void HandleZoom() {
        // Get the distance between the camera and the target object
        float distance = Vector3.Distance(camera.transform.position, transform.position);

        // Calculate the new field of view based on the distance
        float fov = Mathf.Lerp(maxZoom, minZoom, distance / 100.0f);

        // Set the camera's field of view
        cinemachineCam.m_Lens.FieldOfView= fov;

        // Zoom in/out using the mouse scroll wheel
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        transform.position += camera.transform.forward * scroll * zoomSpeed;
}
#

here is the new code but no effect

spiral ibex
#

I am not familiar with getting mouse wheel. Is Input.mouseScrollDelta not fitting your requirements?

solemn star
solemn star
#

Hey @spiral ibex thank you. Input.mouseScrollDelta worked perfectly fine. IDK what I did wrong back then.

spiral ibex
#

ยฏ_(ใƒ„)_/ยฏ

arctic marsh
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
    public List<Inventory_BaseClass> inventorySlots;
    public static Inventory inventoryInstance;
    public static Inventory Instance => inventoryInstance;
    // Start is called before the first frame update
    void Awake()
    {
        
        if (inventoryInstance == null)
        {
            inventoryInstance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

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

public class DisplayItems : MonoBehaviour
{
    public Inventory refInventory;
    public List<Inventory_BaseClass> refInventorySlots;
    // Start is called before the first frame update
    void Awake()
    {
        refInventory = FindObjectOfType<Inventory>();
        refInventorySlots = refInventory.inventorySlots;
    }

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(refInventorySlots.Count);
    }
}

Whenever I reopen the scene that initially has the first script, the inventorySlots list is completely cleared, does anyone know why?

runic skiff
#

I'm making Breakout/Brick Breaker. My bricks change color as they decrease in HitPoints (similar how balloons work in Bloons Tower Defense games). A brick modifies its Sprite Renderer in the set component of the HitPoints property, so when HitPoints is changed, the sprite is automatically updated. A brick's maximum hit points is determined by a serializable field. How can I make a brick automatically change its sprite when its maximum hit points field is updated in the editor? i.e. In edit mode?

leaden ice
runic skiff
somber nacelle
#

you'll need to assign to the backing field if you're using OnValidate since the SpriteRenderer property is only assigned in Awake which only happens at runtime, but OnValidate happens at edit time

runic skiff
#

RIGHT! Thank you!

somber nacelle
#

however doing so won't update the sprite which was why you were assigning to the property

runic skiff
#

Actually, I'm a bit confused...

dusk apex
somber nacelle
# runic skiff Actually, I'm a bit confused...

if you use an explicit backing field for the sprite renderer that you assign in the inspector (or expose the automatically generated backing field to the inspector) you won't have to worry about that (though you should still null check the sprite renderer before changing its sprite property just in case

molten thicket
spiral ibex
cerulean oak
#

I cant manage to get serialization to work fine on a scriptable object.
I have an array of custom objects (marked with [Serializable]) that dont seem to get serialized.
I dont know what else to try at this point

somber nacelle
spiral ibex
#

whoops, sorry :p

runic skiff
arctic marsh
spiral ibex
arctic marsh
somber nacelle
cerulean oak
sweet bronze
#

what IDE I should not use? seems like there are issues with vscode?

cerulean oak
sweet bronze
#

okay, just had some issues with vsc, reinstalling it to see if that helps.

runic skiff
somber nacelle
arctic marsh
somber nacelle
arctic marsh
#

theres been a few updates here and there, those are the most up-to-date.

sweet bronze
cerulean oak
#

ok makes sense

dusk apex
cerulean oak
#

in java you can serialize final fields with reflection magic

#

thought it would be the same in C#

#

i'll create getters

#

and make them private I guess

#

can it serialize private fields?

spiral ibex
dusk apex
arctic marsh
sweet bronze
#

Ok, I'll pass on vsc then. I'll try VS but even there I had issues with code completion

spiral ibex
dusk apex
arctic marsh
dusk apex
#

If using Hub to install, just ignore the download step in manual and do the rest.

sweet bronze
#

!ide

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.

somber nacelle
runic skiff
dusk apex
#

It will not by default

cerulean oak
sweet bronze
fathom geode
#

is there a way I can set up unity events (or any other way to call simple methods) with scriptable objects?
An example of intended behavior would be having an empty game object with the unity event on it (because then it can reference the methods I need), but it would be easier for my designers if it was a scriptable object because the methods it calls are identical across scenes

#

I thought I could just put unity events as a variable in a scriptable object and call it a day, but it can't actually reference any methods in my scene

spiral ibex
#

ScriptableObjects exist within your project. Referencing scene objects is not what they're made for.

fathom geode
#

I understand that part, but the methods I need to reference are static. I know unity events probably won't work for this, I'm looking for suggestions for similar functionality (where I can expose which methods get called in a designer-friendly way)

#

effectively, what has been requested is a stack of methods where the order can be changed easily. I figured scriptable objects were a good way to structure it, but I'd like to not need to hide it all behind an enum with a hardcoded reference to each method (which is the only other idea I have right now)

spiral ibex
#

I never tried it, can you create methods within your scriptableobject that executes these static methods, then link the object itself and select them?

fathom geode
#

nope, I tried that as well

dusk apex
#

Certainly it'd be able to reference those methods from itself

sweet bronze
#

@dusk apex I guess code completion doesn't work by the looks of it?

sweet bronze
#

yeah it's weird because I have it set up like this

dusk apex
#

Did you complete all of the steps?

sweet bronze
#

I believe so, let me restart Unity

fathom geode
cinder monolith
#

The Animator Controller (TileAnimController) you have used is not valid. Animations will not play what this mean and how do i fix

sweet bronze
dusk apex
sweet bronze
dusk apex
#

Also, try restarting VS

sweet bronze
#

However I think there might be some other issues with the project itself

sweet bronze
#

thank you

runic skiff
spiral ibex
runic skiff
cinder monolith
#

how do i play an animation

spiral ibex
cinder monolith
#

thanks

#

what is a state hash name

arctic marsh
dusk apex
#
[CreateAssetMenu(fileName = "ExampleSO", menuName = "ScriptableObjects/ExampleSO", order = 1)]
public class ExampleSO : ScriptableObject
{
    public UnityEvent exampleEvents;
    public void Print(string str) => Debug.Log($"{name}: {str}");
}```
spiral ibex
spiral ibex
arctic marsh
cinder monolith
#

The Animator Controller (TileAC) you have used is not valid. Animations will not play

#

why does it keep saying this

#

unity after making their animation system unnecessarily complicated:

earnest gazelle
#

Is it guaranteed Awake or OnEnable of a scriptableobject is called in runtime (after building on device)?
That scriptable object has bee assigned into a mono script in a scene. I mean it has not been created at runtime.

leaden ice
hallow fjord
#

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

earnest gazelle
leaden ice
#

read it again

#

they talk about runtime as well.

somber nacelle
earnest gazelle
#

I want to get a data from disk at the beginning in a scriptable object and then use it.
I decided to get data in editor time and then serialize it

earnest gazelle
#

OnInitializeLoad?

spiral ibex
#
public Data myData;
public Data MyData{
get{
  if(myData == null){
//load from disk
}
return myData;
}
}
#

something like this

earnest gazelle
# leaden ice read it again

Creating a new scriptable object in the project, during editor time:
Only the created scriptable object

  1. Awake()
  2. OnEnable()

Script reload:
All Scriptable objects in the project

  1. OnDisable()
  2. OnEnable()

Scriptable object instantiated at runtime:
Only the instantiated scriptable object

  1. Awake()
  2. OnEnable()

Scriptable object instance destroyed at runtime:
Only the destroyed scriptable object instance

  1. OnDisable()
  2. OnDestroy()

Editor startup:
All Scriptable objects in the project

  1. Awake()
  2. OnEnable()

Destroying an object in the project, during editor time:
0. No callbacks are called

I see only Scriptable object instantiated at runtime:

#

I do not instantiate it in runtime by ScriptableObject.CreateInstance()

warm hedge
#

Where is the Visual Scripting section?

leaden ice
#

this part

warm hedge
sweet raft
#

Is OnDisable not called the first time a GameObject gets SetActive(false)?

Scenario...

  • Scene starts with GameObject in question inactive.
  • Through player input the GameObject gets SetActive(true).
  • Through player input the GameObject gets SetActive(false). ...but OnDisable does not trigger.
  • Through player input the GameObject gets SetActive(true) again...
  • Through player input the GameObject gets SetActive(false) again...and THIS time OnDisable triggers.
cinder monolith
#

how do i get a child of a gameobject

earnest gazelle
dim whale
# sweet raft Is OnDisable not called the first time a GameObject gets SetActive(false)? Scen...

It is called every time the game object is disabled.
Here's some code I use for testing.

using UnityEngine;
public class MonoExecutionOrder : MonoBehaviour
{
    private void Awake() { Debug.Log(gameObject.name + "\tAwake\t\t" + Time.time.ToString("F7")); }
    private void OnEnable() { Debug.Log(gameObject.name + "\tOnEnable\t\t" + Time.time.ToString("F7")); }
    private void Reset() { Debug.Log(gameObject.name + "\tReset\t\t" + Time.time.ToString("F7")); }
    private void Start() { Debug.Log(gameObject.name + "\tStart\t\t" + Time.time.ToString("F7")); }
    private void FixedUpdate() { Debug.Log(gameObject.name + "\tFixedUpdate\t\t" + Time.time.ToString("F7")); }
    private void Update() { Debug.Log(gameObject.name + "\tUpdate\t\t" + Time.time.ToString("F7")); }
    private void LateUpdate() { Debug.Log(gameObject.name + "\tLateUpdate\t\t" + Time.time.ToString("F7")); }
    private void OnDisable() { Debug.Log(gameObject.name + "\tOnDisable\t\t" + Time.time.ToString("F7")); }
    private void OnDestroy() { Debug.Log(gameObject.name + "\tOnDestroy\t\t" + Time.time.ToString("F7")); }
}
sweet raft
#

Weird...

dim whale
runic skiff
somber nacelle
#

Serialize the field like I suggested earlier then just drag the reference in, no need to GetComponent in OnValidate

sweet raft
dim whale
#

Happy coding!

sweet raft
runic skiff
somber nacelle
#

Yes

cinder monolith
#

how do i get the camera in a 2d unity project

#

c#

slow grove
#

Hey guys, couple questions:

  1. Whenever you're using scenemanager to additively load scenes, do all of the scenes need to be present in build settings?
    and
  2. If I additively load a scene, say Scene B into Scene A, is there any way I can access the contents of scene B from scene A via a script?
west sparrow
# slow grove Hey guys, couple questions: 1) Whenever you're using scenemanager to additively...
  1. Yes
  2. It looks like most people are using a static reference

There is a heavy method you can use here if needed though:
https://answers.unity.com/questions/1826841/find-gameobject-in-another-loaded-scene.html

#

FindObjectsOfType should work for all loaded and active scenes though
More examples: https://gamedev.stackexchange.com/questions/126232/get-all-objects-of-additively-loaded-scene-loadscenemode-additive

slow grove
#

Gotcha, so I'm trying to load in levels as players get near them, is putting the levels in seperate scenes the way then? Or is it better to store them as prefabs instead

leaden ice
#

and the overall flow of your game

slow grove
#

It's an open world kind of deal, but locations need to be loaded in as players get close. The caveat is that the main scene cannot be unloaded as it has like skybox elements

leaden ice
#

It can be done either way

#

if you use prefabs you'd want to be using Addressables though

slow grove
#

Gotcha, so there's no like "right" way right?

leaden ice
#

One thing though is that in Unity - scenes are the unit of thing that baked global illumination and baked occlusion culling are associated with

#

so if those things are important in your game, scenes are probably the way to go

slow grove
#

Gotcha, thanks!

slow grove
glossy basin
#

Hello there, Im following a tutorial on doing mesh generation like minecraft; the code works fine but I would like to add caves, I know I would need to use 3D perlin noise, but my question here is how do I modify my conditional so that I can use 3D noise? like what do I compare the current height with?

leaden ice
slow grove
#

ohh, I didnโ€™t know that, neat

#

thanks! (Again)

daring spade
#

quick question im getting the error that Time does not contain a definition for delta time and am wondering why that would be heres the code

quartz folio
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.

fathom geode
daring spade
glossy basin
mystic ferry
#
      _uiCanvas = Instantiate(_uiCanvasObject, Vector2.zero, Quaternion.identity); //initializing UI at runtime
      _winCanvas = Instantiate(_winCanvasObject, Vector2.zero, Quaternion.identity);
      _pauseCanvas = Instantiate(_pauseCanvasObject, Vector2.zero, Quaternion.identity);
      _uiCanvas.SetActive(false);
      _winCanvas.SetActive(false);
      _pauseCanvas.SetActive(false);
#

is there any way to shorten these calls?

unkempt sail
#

not really

#

if you need to assign the game object then set some state for it, those are two separate operations

#

best you can do is make an game object extension that adds a boolean at the end of the function call to indicate the gameobjects activeness

#

I am trying to make a shotgun script, it basically does a loop for how many "pellets" I want to shoot, then use a projectile script I use to add the actual speed, I also added a bit of random spread to make it more shotgunny

#

and even though I am adding different randomness to each pellet they still go in the same direction

#

code that spawns the pellets and adds random direction: cs for (int i = 0; i < pelletCount; i++) { Projectile p = Instantiate(pellet, shootPoint.position , Quaternion.identity); var newDirection = direction.normalized + spread * (Random.value - 0.5f) * 2; p.Shoot(newDirection); }

#

code that shoots the projectile:

public void Shoot(Vector3 direction, bool addTourqe = false, bool addUpwards = false)
{
    if (addUpwards) direction += Vector3.up * speed / 10f;
    if (addTourqe) rigidbody.AddTorque(Vector3.right * speed, ForceMode.Impulse);
    
    transform.forward = direction;
    rigidbody.velocity = speed * transform.forward;
}```
#

I've endlessly debugged, and even implemented different ways of adding the spread like through spinning the projectile in a random direction then shooting it

#

and I even made sure that randomDirection always does return different values for each iterations

#

I feel like I'm missing something super obvious

gloomy swan
#

Should I preload the gameplay element from the main menu? Like UI, Photon, Camera, Character,... ? Since those element will always be in gameplay and I can keep data like player equipment from the main menu into gameplay

gloomy swan
#

It's like levels

#

So each levels will have a different scene

#

And thereโ€™s about hundreds of them

#

After each levels player goes back to the level select to goes on to the next level

polar marten
#

hmm

#

photon... this is a multiplayer game?

#

@gloomy swan do you have a screenshot?

ruby fulcrum
#

how is it still giving me this error

context: script belongs to a distractor object, which purpose is to track the closest enemy to it and call the distract() function in the enemy script

if (closestEnemyAI != null && gameObject)
            {
                enemyAiScript.distract(gameObject);
            }

Error:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
EnemyAI_Script.distract (UnityEngine.GameObject distractor) (at Assets/Scripts/EnemyScripts/EnemyAI_Script.cs:324)
Distractor_Script.startDistractor () (at Assets/Scripts/UncategorizedScripts/Distractor_Script.cs:53)
Distractor_Script.Start () (at Assets/Scripts/UncategorizedScripts/Distractor_Script.cs:66)
gloomy swan
tepid jewel
# polar marten what is `MeshExtrusion`?
GitHub

Spline based mesh generation. Contribute to nickhall/Unity-Procedural development by creating an account on GitHub.

tepid jewel
worldly hull
#

im asked to create a quest system where quest is unlocked based on real life time, server based

just like when player finished the part 1 of the quest, part 2 will be unlocked after certain timer, maybe its 1hr , 1 day or 2 days

my idea is to record the date/time on the moment that user finished the quest, and then unlock the quest after the set timer

#

but where should i do the validation? i cant do it on update to constantly grab and compare info from server , and how to calculate the time

hard estuary
hard estuary
worldly hull
#

i think i will go for first one

#

i just had a discussion with my team, they decided to go on the first one

thorny sparrow
#

Hello, how can I move a sprite in a circle without rotating it?

worldly hull
#

thx๐Ÿ‘

wicked urchin
thorny sparrow
#

ok... but how

wicked urchin
thorny sparrow
#

the link without the sass would be appreciated

severe marsh
plucky inlet
#

You should know, what features you added, how should we know. Maybe show your script, so we know what you talk about. Does your inventory system block inputs maybe, did you disable scripts for testing and forgot to reenable?

#

We are in a code channel, so show your code...

#

yeah, otherwise you just get lose suggestions here cause noone knows, what you did and it could be everything...

#

Rigidbody removed, velocity set in update, set to kinematic, game paused with timescale, added huge mass, commented out the script part, blocking inputs with another action so you dont fire your script... etc etc etc

amber mica
#

Hello! I need some advice about to move a rigidbody properly on slopes. I move my rigidbody modifying velocity vector. The problem is very basic: on steep slopes character speed drops. I am looking for some tutorial to handle this. I already have some raycasting to check if rigidbody is grounded and I think I could do some calculation on ground normal or something like that, but I can't figure it out. Some advice?

rough shuttle
#

SpawnTimeMin : 5
SpawnTimeMax : 8
DistMin : 15
DistMax : 35

Anyone know how I can have one Variable (ManageCreep) who's min value is 0 and max value is 1 to handle both SpawnTime and Dist min and max together?

plucky inlet
plucky inlet
somber nacelle
rough shuttle
#

but I only want to change ManagerCreep that in turns changes the other two accordingly

plucky inlet
#

Then you would use getters and setters to update those values based on another one

rough shuttle
#

trying to find examples but I dont get it

plucky inlet
#
[SerializeField]
    public int strength
    {
        get {return m_strength; }
        set {m_strength = value; }
    }
    public int m_strength;
#

This is how you can get and set values. from there you can go and do whatever you need to change on your variables

#

And through what would you switch? All floast that are possible from 0.000 to 1.000 ?

#

He wants to set two OTHER values to a specific mathematical relation to a MAIN VALUE, so he could just use get to get the main value + his calculation

#

Dont overcomplicate things here. Or he could also just use a public void to set them if he wants to rely on methods

rough shuttle
#

Ok I got it! thanks guys ๐Ÿ™‚

plucky inlet
#

Nope, if they are in the inspector, those will be the default values for the build

#

Unless you change them by code ๐Ÿ˜‰

#

No no, inspector values will always be exported as default values. Even if you lets say first write public float myFloat = 20, then change it inspector, the inspector value will override the 20 in your code when initialised.

warm mesa
#

Hi, I am trying to set the timer for 1hr but the script is not working beyond 90000 ms(miliseconds). Here is the script Link:https://hastebin.com/share/vakemidufa.csharp

plucky inlet
# warm mesa Hi, I am trying to set the timer for 1hr but the script is not working beyond 90...

I suggest look into this post: https://answers.unity.com/questions/1193407/make-a-countdown-timer.html
Especially how to compare datetimes and use the ToString() method to print out your desired values without weird calculations ๐Ÿ™‚

glad nacelle
#

Hello, I've created this static class and I'm trying to call the SendJson function from another script but it's not getting called

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;


public static class JsonSender
{
    public static void SendJson(string json)
    {
        MonoBehaviour reference = new MonoBehaviour();
        reference.StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
        Debug.Log($"World");
    }
}

public class ProceedToSendJson : MonoBehaviour
{
    public void ClickToSendJson()
    {
        Debug.Log($"hello");
        string json = UserDataManager.instance.ToJson();
        JsonSender.SendJson(json);
    }
}

I get "hello" but not "World"

thin aurora
glad nacelle
#

yes

thin aurora
# glad nacelle yes

Can you place a log before MonoBehaviour reference = new MonoBehaviour(); and test if that logs?

glad nacelle
#

ok wait

thin aurora
#

Considering your method content is invalid, it might be blocking

quartz folio
#

You cannot new a Monobehavior

#

So this is a fundamental problem with your setup

#

Just pass the caller to the function and use that to start the coroutine

glad nacelle
glad nacelle
#

I mean should i remove MonoBehaviour reference = new MonoBehaviour();

quartz folio
#

Yes

#

Pass the instance of the caller to the function instead

glad nacelle
#

okay

thin aurora
#

Yes, that basically

#

I'm guessing your script is blocking because of it

glad nacelle
#

ok so the entire script looks like the following, now SendJson is getting called but not the SendRequest() which either logs "error" or "success" message

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;


public static class JsonSender
{
    public static void SendJson(string json)
    {
        Debug.Log($"world");
        // MonoBehaviour reference = new MonoBehaviour();
        SendRequest(ApiUrls.PostDataUrl, json);
    }

    private static IEnumerator SendRequest(string url, string json)
    {
        // Create a new UnityWebRequest object
        var request = new UnityWebRequest(url, "POST");

        // Set the request's content type to "application/json"
        request.SetRequestHeader("Content-Type", "application/json");

        // Convert the JSON string to a byte array
        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);

        // Set the request's upload handler to upload the byte array
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);

        // Set the request's download handler to download data to a byte array
        request.downloadHandler = new DownloadHandlerBuffer();

        // Send the request and wait for a response
        yield return request.SendWebRequest();

        // Check if there was an error with the request
        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Error sending request: " + request.error);
        }
        else
        {
            Debug.Log("Request sent successfully!");
        }

        // Dispose of the UnityWebRequest object
        request.Dispose();
    }
}
knotty sun
knotty sun
#

yes, except the MonoBehaviour reference needs to be a parameter not declared in the method

glad nacelle
#

can you tell me how? I did not understood.

knotty sun
#
public static void SendJson(string json, MonoBehaviour reference)

then to call it

JsonSender.SendJson(json, this);
glad nacelle
#

ok let me try

#

btw SendJson is my custom made function and not some package. So will it work?

knotty sun
#

yes

vague slate
#

Am I doing gitignore correctly?

# Type cache
/[Aa]ssets/[Rr]esources/[Mm]VVMToolkit.meta
/[Aa]ssets/[Rr]esources/[Mm]VVMToolkit/*
#

for some reason it doesn't work

hybrid flare
#

any help, getting this error: Assets\TsTubeMove.cs(26,18): error CS1061: 'GameObject' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

thin aurora
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.

hybrid flare
#

what?

thin aurora
hybrid flare
#

how do i configure it

thin aurora
vague slate
hybrid flare
#

okay thanks

thin aurora
# glad nacelle Hello, I've created this static class and I'm trying to call the SendJson functi...

This won't work because an IEnumerator yields and pauses. This is c# behaviour and if you call it manually, the code will stop at yield return request.SendWebRequest();. StartCoroutine fixes this by making Unity handle the yield operations based on what must be yielded. You can't properly handle a Coroutine unless you manually implement a handler for it, which is way too complicated and unneeded.

What you could be doing is making your method asynchronous. Then you can send your method and asynchronously wait for a result.
Problem is, this is complicated.

Another solution is making this JsonSender a singleton, and have it inherit from a MonoBehaviour:

--   public static class JsonSender
++   public class JsonSender: MonoBehaviour
     {
++       public static JsonSender Instance { get; private set; }

++       private void Awake()
++       {
++           Instance = this;
++       }

        public static void SendJson(string json)
        {
--          MonoBehaviour reference = new MonoBehaviour();
--          reference.StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
++          StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
        Debug.Log($"World");
        }
    }

    public class ProceedToSendJson : MonoBehaviour
    {
        public void ClickToSendJson()
        {
            Debug.Log($"hello");
            string json = UserDataManager.instance.ToJson();
--          JsonSender.SendJson(json);
++          JsonSender.Instance.SendJson(json);
        }
    }

Notice how you can use StartCoroutine like normal now.

#

You just need to add it to a component, and it will work.

late lion
glad nacelle
tepid river
#

do they show up in git status?

thin aurora
vague slate
tepid river
#

not familiar with that view. type "git status" into your terminal in the git repo

glad nacelle
#

ok so as you said the SendRequest() will stop at yield, so if I add a log message at the top of the function will it log?

thin aurora
glad nacelle
#

i tried that but it didn't log that message

#

ohh

thin aurora
#

My mistake, you specifically need to call Current on it to get the value

#
var enumerator = SendRequest(ApiUrls.PostDataUrl, json);
var first = enumerator.Current;
    enumerator.MoveNext();
var second = enumerator.Current;

Something like this

glad nacelle
#

ohk ohk

thin aurora
#

Unity does this internally when you use StartCoroutine

glad nacelle
thin aurora
#

If it works, it's fine

#

I would argue you make it asynchronous and upload using a HttpClient instead of the build in Unity solution but that's just more complex

glad nacelle
#

got it

velvet quartz
#

If on my Update i run a coroutine with yield for a frame does that pause my update loop or not ?