#archived-code-general

1 messages ยท Page 344 of 1

elfin tree
#

had no idea

crude elm
#

Hi,

I'm trying to solve a context steering issue when the desired movement matches obstacle direction i.e. the target is behind the obstacle. Most steering behaviours I've seen doesn't account for that out of the box.

Should this be a combination of movement context and stronger avoidance context, or there is a trick to mapping obstacles direction?

elfin tree
#

What would be the best way to convert a TimeSpan to a delay in a coroutine?

#

Normally I use WaitForSeconds but TimeSpan.TotalSeconds returns a double, same for milliseconds

#

I get that TimeSpan by substracting two DateTime, but I could do something else with the two DateTime

late lion
elfin tree
#

Like how are miliseconds a double

late lion
elfin tree
#

ty

rain crater
#

Hey, does anyone have any idea why this function causes Unity to get stuck on reloading domain, when I start a game, call it, and then stop play mode and try to start again?

public async void NATPunch()
    {
        var discoverer = new NatDiscoverer();
        var cts = new CancellationTokenSource(2000);
        var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

        if (device != null)
        {
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "game"));
            await device.CreatePortMapAsync(new Mapping(Protocol.Udp, port, port, "game"));
        }
        else
        {
            cts = new CancellationTokenSource(2000);
            device = await discoverer.DiscoverDeviceAsync(PortMapper.Pmp, cts);
            if (device != null)
            {
                await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "game"));
                await device.CreatePortMapAsync(new Mapping(Protocol.Udp, port, port, "game"));
            }
        }

        Debug.Log("Function ended"); //This prints
        return;
    }```
I'm using Open.NAT to do port forwarding in my game, and I'm doing stuff according to how it says on their github. The function normally gets to the end (the debug log prints) but then happens what I said. I've heard some stuff about async function not being the best with Unity, so I guess it might be something with it. 
And it seems like this function causes problems, because making it return immediately after calling it makes everything work
#

(If this is not Unity-specific enough, which it might be, please let me know, i'll go ask somewhere else)

knotty sun
rain crater
#

just a normal call NATPunch(); from a normal method
I tried to make cts = null, unless you mean the .Dispose() thing (i'll try it now)

#

tried the Dispose thing, it doesn't help

#

technically I could just not call this function in the editor, but then it would be nice to fix it, so it doesn't do some weird things in build (just noticed - when I try to stop the game it freezes, like Unity on domain reload)

glad sundial
#

Hello, I have a simple question. How can i do to detect if an active GO is triggered on my disabled GO ?
I tried to create an empty GO and add trigger class but didn't work well ...

serene stag
glad sundial
#

yes i know

#

that's why i create a empty GO

#

I copy every properties but it didn't work well

leaden ice
serene stag
#

you are trying to do a collision between enabled go and disabled go and checking ontrigger.

#

disabled go never detects collisions.

glad sundial
#

I'll add some context. I have a GO (my agent) and I have an item that spawns on 2 platforms randomly. I don't want the item to spawn if the agent is already on the spawner. So the disabled GO is the item and the active GO is the Agent

glad sundial
#

my English is very limited. That's why it's hard to understand me. I'm really sorry !!!

serene stag
#

then why make the item go disabled just make the script which is spawning disable when the agent is on the spawner platform simple.

glad sundial
#

No, I can't do that because as there are several spawners, I just have to make sure that they don't spawn on the platform where the item is supposed to spawn.

#
private void Update()
    {
        if (NbItemSpawned == 0) // No item on stage
        {
            GameObject randomItem = RandomizeSpawn(); // Get random item and random platform
            m_SpawnChecker.SetItem(randomItem); //Setup trigger checker for item

            if (!m_SpawnChecker.get_IsTriggered()) // GO not triggered
            {
                NbItemSpawned++; // Update nb items
                randomItem.SetActive(true); // Active item
            }
        }
    }
...
TriggerClass.cs:

public void SetItem(GameObject item)
    {
        m_IsTriggered = false; // Reset value
        gameObject.transform.SetParent(item.transform.parent); // Set Item parent
        
        // Copy Transform
        gameObject.transform.localPosition = item.transform.localPosition; // Copy localPosition
        gameObject.transform.localRotation = item.transform.localRotation; //Copy localRotation
        gameObject.transform.localScale = item.transform.localScale; //Copy localScale
        
        // Copy Box Collider
        BoxCollider itemCollider = item.GetComponent<BoxCollider>();
        m_TargetCollider.center = itemCollider.center; // Copy center
        m_TargetCollider.size = itemCollider.size; //Copy size
        m_TargetCollider.isTrigger = itemCollider.isTrigger; //Copy trigger state
        
        gameObject.SetActive(true);
    }

Mb what I'm trying to do will help

vale bridge
#
leftMouseClick_prev += Time.deltaTime;
rightMouseClick_prev += Time.deltaTime;
midMouseClick_prev += Time.deltaTime;
jumpPressed_prev += Time.deltaTime;
#

Is there a better way to do these crude deltatime counter increases

#

Also was wondering if I should check isGrounded in update or fixedUpdate, I imagine it would be the latter?

heady iris
heady iris
swift falcon
#

i have a quad object which has a videoplayer component inside it how do i access it in my code i have tried different approaches but doesnt work

#

its a simple play and pause function but doesnt work

#

Using a variable that is inside the class prevents the lambda to get pooled and it creates lambda every time. But why? Here's the compiled version to show you. Look at the M() in right side.

heady iris
#

I'm more surprised that the compiler managed to avoid creating garbage in the first case!

#

The first anonymous function captures no variables.

#

It only depends on its arguments

#

The second anonymous function captures a variable.

swift falcon
#

Oh

#

So it is because the object may be changed in runtime

heady iris
swift falcon
#

the quad is not in the scene

heady iris
#

so it's on a prefab, then..?

swift falcon
#

yeah

swift falcon
heady iris
#

then store a reference to the VideoPlayer when you instantiate the prefab.

balmy raptor
#

Hi, what would be the best channel to post a question I have about Unity As Library for Android Studio?

swift falcon
#

the prefab is spawned by XR origin

#

i followed the instructions

#

but how do i get to the videoplayer

#

for instance the video player is a component of a child inside the parent prefab

fresh hazel
#

Hey, so I'm making a project with Unity but I have huge lags and my profiler looks like that
It looks like the major issues are the EditorLoop and the RenderLoop, but I'm not sure what it mean exactly and how I can know what the problem is exactly?

heady iris
#

EditorLoop can be a bit misleading (in both directions)

#

I've seen situations where EditorLoop is obviously counting time taken to render the scene

#

but it can also add some very nasty lag spikes that won't actually happen in the built game

#

Full-screening the game view can help -- this stops unity from having to draw the inspector

#

which can get really expensive

old linden
#

Hi. I'm wanting to rotate around the Player given a fixed radius above the Player, whilst the player is moving but without parenting. I have the following code which works fine, but when the player moves, the camera increases its radius, instead of maintaining the same distance. What's the best way to do this?

umbral fox
#

Unity2022 LTS ... exiting play mode triggers Awake + Start + OnEnable ... anyone know when/why/how this was changed?

Seems to happen whenever I subclass Graphic (nothing else needed to trigger it)

#

(or is this something that's always been true with Graphic and I somehow didn't notice before? Seems very unlikely, but I guess possible I didn't know!)

heady iris
#

Graphic has [ExecuteAlways] on it.

#

this allows for things to update as you work on your UI in edit mode

umbral fox
#

Has this always been the case? I am 99% sure it didn't used to do that (and specifically: I had to add it to subclasses when I wanted that behaviour)

#

But maybe I'm just losing my mind ๐Ÿ™‚

heady iris
#

Unity UI has barely changed in a long time

#

It may have changed from [ExecuteInEditMode] to [ExecuteAlways], but that just indicates that it's safe to run in prefab isolation

umbral fox
#

That's not true. e.g. 2022 fundamentally broke UnityUI in multipe places :).

#

Also: UIToolkit team has repeatedly broken UnityUI in each major Unity release for years, to support/hide/workaround their own bugs.

heady iris
#

what?

umbral fox
#

Other than by installing old editors and manually reviewing the Unity source ... any suggestions on how I could verify it's always been like this / whether it changed recently? ... doesn't matter at this point, just want to check if I'm losing my memory ๐Ÿ™‚

umbral fox
heady iris
heady iris
#

link me to the bug reports on the issue tracker.

#

I should point out that custom property drawers and custom editors have nothing to do with UGUI

#

they use either UIToolkit or immediate-mode graphics

umbral fox
#

Sorry, my friend, that's simply not true. UI Toolkit made some changes to how events are delivered that specifically broke all custom property drawers that were written WITHOUT UI Toolkit if you had both present in the same project.

#

I wasn't impressed, and the final response I got from them was essentially: Yes but we want everyone to use UIToolkit, so you need to replace all your existing property drawers with UIT property dtawers.

#

(Fine, I was able to do that with my own code - but it meant we had to drop some 3rd party code/assets until they were all using uit too)

heady iris
#

I cannot find anything on the issue tracker.

umbral fox
#

Tried to fish out bug numbers for you, but I didn't keep copies of old emails when projects ended (I asumed I could always go back into fogbugz if I needed to re-read them).

heady iris
umbral fox
#

I asked around other studios at the time - most weren't using custom property drawers, so it didn't affect them - or they were heavily customising their editors and had already upgraded everything to UIT.

winter bramble
#

Bike shedding question for anyone who has tried. I want to create a room editor game in which users could load and execute assets during runtime. i.e. import a .zip that includes game "furniture" (really .lua scripts or other interpreted langs I build the interpreter for like js, and then other binary assets .fbx files, audio files, etc.) which can be placed in the game and persisted.

Wonder if Unity would be a good choice for this, or if im better off solving the whole runtime system in my own engine... (obv realize the my own part is reinventing / building a massive amount of what unity provides, I just want to emphasize the runtime part.)

umbral fox
#

(I moved all my editor-drawers code to UIT, and other than being careful waiting for 3rd party code to update, stopped caring)

umbral fox
heady iris
#

I know that there are assets for runtime model import

#

Unity can decode audio at runtime...but only when loaded from the web, bafflingly

#

I don't think it can decode an mp3/ogg that you've stored locally.

winter bramble
# umbral fox Which is hte part that you think might not be a good fit for Unity? There are pl...

Good question, I am bit shakey of the common architectures that represent this "realtime 3d runtime asset plugin system" but I suppose the fact that if I want to say execute player added scripts at runtime to interact with "Unity's runtime" there could be some integration issues / limitations / extensions that would make this harder because the whole point of this game is this part, the rendering isnt going to be fancy. Id also like to be able to accomodate shaders at runtime and more fancy player added things... feels like the integration here is the thing I sense might be very hard to do it the Unity way.

winter bramble
heady iris
#

There are, of course, libraries you can use to decode MP3/OGG

#

and then use SetData

#

Custom user scripting is another beast. I haven't touched that at all yet.

#

Something like Lua would be reasonable.

umbral fox
#

There's many examples of doing it, from embedding an interpreter (fine on most platforms, but e.g. when doing mobile you need to first check that your preferred interpreter actually compiles into IL2CPP correctly, and that Apple etc will allow it), to implementing your own cut-down language by hand, and many assets that will do either/both/etc for you (can't recommend any off the top of my head, but I've seen and used several, and implemented our own interpreterst from scratch for simple languages, and implemented our own custom langauges for simple in-game scripting).

winter bramble
#

I see. Good to hear itโ€™s not ringing any donโ€™t do this alarms. I suppose what I really want to build is a game that supports mods. I suppose they donโ€™t need to be โ€œinjectedโ€ at runtime. Is there a cleaner more trivial solution if they donโ€™t need to be added at runtime but instead pulled in from some menu and then restart? Ideally creating and publishing mods could be done in Unity separately and then just exported as a module. I guess Iโ€™d love any resources on mod architectures in Unity ๐Ÿ™‚

leaden ice
heady iris
#

mildly cursed

unique delta
#

is it posible to remove an element from a list by name?

leaden ice
#

Only by iterating over the list until you find it

#

If you need to do things by name you should look into a Dictionary instead of a List

heady iris
#

well, there is RemoveAll

#
nums.RemoveAll(item => item % 2 == 0);
#

this deletes all even numbers from the list

#

I want to be able to memoize a bunch of classes. That looks like this:

Dictionary<ValueTuple<Foo, Bar>, MyClass> memoized = new();

protected MyClass(Foo foo, Bar bar) { /* constructor goes here */ }

public MyClass Memorize(Foo foo, Bar bar) {
  var tuple = ValueTuple.Create(foo, bar);

  if (memoized.TryGetValue(tuple, out var result)) return result;

  result = new(foo, bar);
  memoized[tuple] = result;

  return result;
}

So, if an instance has already been created with those exact arguments, just return the instance. If not, create a new instance and put it in the dictionary.

#

This works fine, but it's a decent bit of manual fiddling for each class.

#

I'm wonder if there's any way I could make this easier.

#

maybe i can create a separate "Memoizer" class (that would require a public constructor, but oh well)?

unique delta
#

can t i use this : list.RemoveAt(Convert.ToInt32(GameObject.Find("...."); ?

heady iris
#

i mean, sure, if the name of the game object is the index you want to remove from the list..

#

but that seems very weird

unique delta
#

it s perfect for me

swift delta
#

not to bump off fen's question but what's a good method to ensure a bullet going somewhat fast doesn't phase through colliders? some googling suggested attaching a raycast to the bullet and use its rigidbody as the ray's direction and distance (via magnitude) but I wanted to make sure that'd be a good idea

lean sail
# unique delta it s perfect for me

does that even work or compile? finding a gameobject, then converting to int, and that magically being the index of in a list?
looks like AI code

swift delta
#

it's worth noting the issue lies in thin colliders, such as floating targets

heady iris
heady iris
swift delta
#

I remember switching it to other collision detection methods but didn't have much luck

#

let me check something

heady iris
#

Note that both the bullet and the target need non-default modes

unique delta
heady iris
lean sail
#

then no it definitely does not work

swift delta
heady iris
#

I believe it can still be kinematic.

swift delta
#

wack. how about interpolation on the bullet?

heady iris
#

It has nothing to do with collision detection

swift delta
#

noted

#

continuous dynamic mode on the bullets themselves changed nothing, so I'll go ahead and plug the kinematic rigidbodies on the targets

heady iris
#

These two options have a big impact on physics performance. Alternatively, you can use CollisionDetectionMode.ContinuousSpeculative, which is generally cheaper and can also be used on kinematic objects.

ah, so Continuous on the target with a kinematic rigidbody may not work properly

#

you should check if collisions are working properly at all

#

slow the bullet down or give it a very large collider

swift delta
#

increasing the hitbox's size helps, so yeah

heady iris
#

ah, ok

swift delta
#

specifically behind it, making it wider

heady iris
#

If the targets don't move, then just making the bullets use the Continuous collision detection mode should be sufficient

#

as long as the targets don't have a rigidbody on them!

swift delta
#

I tried just that, but it didn't yield any results with or without the rigidbodies

#

on the targets, that is

#

the bullets' prefab already had its rb settings changes

heady iris
#

show me the bullet inspector

#

also, how are you moving the bullets? are they non-kinematic rigidbodies that you just set a velocity on?

swift delta
#

yeah, they are instantiated and accelerated on creation

#

things are being handled on an onTriggerEnter basis and I'm wondering if that's related

#

the bullet is the one handling said interactions

#
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == owner) return;

        if (other.CompareTag("Player"))
        {
            PlayerOnline playerHit = other.GetComponentInParent<PlayerOnline>();
            Debug.Log("Teste");
            if (IsOwner)
            {
                PlayerOnline ownerPlayer = owner.GetComponentInParent<PlayerOnline>();
                Debug.Log(playerHit.GetTeam().teamTag);
                if (playerHit.GetTeam().teamTag != teamTag.Value)
                {
                    playerHit.Damage(damage);
                }
            }

            if (IsServer)
            {
                Debug.Log("Teste");
                Destroy(gameObject, 1);
            }
        }
        if (((1 << other.gameObject.layer) & groundLayer) != 0)
        {
            col.enabled = false;
            rb.velocity = rb.angularVelocity = Vector3.zero;
            rb.isKinematic = true;
            StartCoroutine("TrailGone");
            if (IsServer)
            {
                Destroy(gameObject, 1);
            }
        }
    }
#

bit of spaghetti here, sorry. we're still feeling our way around online interactions

heady iris
#

oh, this is using triggers, not collision messages

#

I am unsure if continuous collision detection works for those.

swift delta
#

let me swap this out for regular non-trigger collisions

heady iris
# heady iris I want to be able to memoize a bunch of classes. That looks like this: ```cs Di...
    public static class Memoizer<T, V> where T : struct
    {
        private static readonly Dictionary<T, V> Memoized = new();

        public static V Memoize(T tuple, System.Func<T, V> ctor)
        {
            if (Memoized.TryGetValue(tuple, out var result)) return result;

            result = ctor(tuple);
            Memoized[tuple] = result;

            return result;
        }
    }
        public StateActivity Memoize(ActivityData data, Entity entity, EntityState state)
        {
            return Memoizer<(ActivityData data, Entity entity, EntityState state), StateActivity>.Memoize(
                (data, entity, state),
                static tuple => new StateActivity(tuple.data, tuple.entity, tuple.state));
        }

I think it works! But it's also mildly gross.

#

i wish it could at least infer the types of T and V

#

If I didn't need to make the class itself generic (so that I can define a Dictionary<T, V>), I could put the generics on the method itself, and then that could be inferred

#

there is the evil option of storing a Dictionary<Type, Dictionary<object, object>> and keying it on typeof(T), but that results in all of these value types getting boxed

#

and the main objective here is to reduce allocations

swift delta
#

so hey things are working now

#

guns aren't supposed to shove enemies into the Nth dimension lmao

#

should be an easy fix at least. thanks for the help

heady iris
#

Giving bullets a super low mass would be the physically-correct way to solve that

swift delta
#

that does make sense mathematically

#

that somehow made it worse at 0.0001 mass

heady iris
#

are you constantly setting the velocity of the bullet?

swift delta
#

nope, only when fired

#

the bullet has no drag either so it should just keep flying at the same speed it was fired at

#
bullet.rb.AddForce(
    (bulletPoint.transform.forward +
     bulletPoint.transform.right * deviation.x + 
     bulletPoint.transform.up * deviation.y)
     * guns[gunID].bulletSpeed,
     ForceMode.VelocityChange //edited
);
bullet.owner = playerObject;
Destroy(bullet.gameObject, 2);
#

ah I didn't specify its force mode

#

let's try that

#

mhm, that did it

heady iris
#

Ah, right -- you wound up with a bullet that's going really really fast

#

good to see the collision detection still worked lol

#

The default mode is ForceMode.Force, which doesn't really make sense for shooting a bullet

#

you probably had to use a ridiculously high bulletSpeed

#

(50 times what you expected, for a bullet with a mass of 1)

#

using ForceMode.Force means that you're applying a constant force

#

if you apply 1 newton of force in FixedUpdate for 1 second, a 1 kilogram object will accelerate up to 1 meter per seond

#

so doing it for one frame gave you 1/50th of a second of acceleration

swift delta
#

yeah. velocitychange is ignoring its mass, so that should mitigate the issue

#

thanks again for the help

heady iris
# heady iris ```cs public static class Memoizer<T, V> where T : struct { priv...
    public static class Memoizer
    {
        private static readonly Dictionary<Type, object> maps = new();

        public static TMemoized Memoize<TArgs, TMemoized>(TArgs tuple, System.Func<TArgs, TMemoized> ctor)
        {
            if (!maps.TryGetValue(typeof(TArgs), out var mapObject))
            {
                mapObject = new Dictionary<TArgs, TMemoized>();
                maps[typeof(TArgs)] = mapObject;
            }

            var map = (Dictionary<TArgs, TMemoized>)mapObject;

            if (map.TryGetValue(tuple, out var result)) return result;

            result = ctor(tuple);
            map[tuple] = result;

            return result;
        }
    }

Now I'm not the biggest of this this, but it does move the type arguments to the method..

#

it turns out you can do Dictionary<,> to avoid actually specifying a specific type

#

truly awful

#

oh, no, you can't: i just couldn't see the error because i'm not used to Rider's look

simple egret
#

Almost compiles, you need to sync the generic type constraints of TArgs to what the Dictionary requires

#

where TArgs : notnull

heady iris
#

that's not part of the type constraint, is it?

#

because the code is working :p

#

you just aren't allowed to pass null at runtime

simple egret
#

You mentioned an "error", I copy-pasted it in an online compiler and it yelled about TArgs not matching the constraints

heady iris
#

ah, no, this was an error with trying to do Dictionary<,>

simple egret
#

Ah, you can only use these in typeof normally

heady iris
#

yeah

simple egret
#

Unbound generics

heady iris
simple egret
#

Nah it was a hard compiler error, though the compiler is on .NET 8 so it might not exist on Framework

heady iris
#

i barely understand which order these things go in

#

.NET standard, .NET framework, .NET 2: .NET Harder

#

anyway, this does appear to be working

#

gotta do a bit of performance testing

#

woooooooo! big performance gains!

#

3x faster, way way way less GC

#

and I'm at least 70% sure that I can safely memoize these objects

swift falcon
#

Anyone got any idea why the IL2CPP build fails but mono passes? I get this error

#

'hash_compare': is not a member of 'stdext'

#

๐Ÿ˜•

cosmic rain
exotic quiver
#

I'm facing an issue that the unity editor gets unresponsive when using an UnityWebRequest.Get Request. As soon as i use

Debug.Log("right before sending");
yield return pointsRequest.SendWebRequest();
Debug.Log("right after sending");

the editor gets unresponsive and the last thing i can see in the console is "right before sending". What can cause this issue? The same code was running flawlessly a couple of weeks ago

lunar lynx
#

anyone know why Texture2D.GetPixelData() doesn't return the correct pixel count?

Here's my code:

Graphics.CopyTexture(brightnessRenderTexture,0,0,brightnessTexture2D,0,0);
Debug.Log(brightnessTexture2D.GetPixelData<Color>(0).ToList().Count);

brightnessRenderTexture is my RenderTexture at 64px by 64px. same dimensions for brightnessTexture2D.
64 x 64 = 4096
Debug.Logging both RenderTexture and Texture2D widths and heights confirm this.
I copy the RenderTexture Mipmap 0 to Texture2D Mipmap 0.
I count the number of pixels in brightnessTexture2D via GetPixelData().ToList().Count, but it only returns 1024, which is 32 x 32. Looks like it's reading not from mimap 0, but mipmap 1?

mossy snow
cosmic rain
exotic quiver
# cosmic rain Share the relevant code. Are you subscribing to a response callback or something...
public IEnumerator MyFancyMethod()
{
    using (UnityWebRequest pointsRequest = UnityWebRequest.Get($"https://somefancyurl"))
    {
        pointsRequest.SetRequestHeader("Authorization", "bearer SomeBearerToken");
        pointsRequest.SetRequestHeader("Accept", "application/json");

        Debug.Log("right before sending");
        yield return pointsRequest.SendWebRequest();
        Debug.Log("right after sending");
        
        
        //... some other code
    }
}
#

no, just yielding for the response.

cosmic rain
exotic quiver
#

Unfortunatelly, did already check the logs. no further messages. it just freezes, no crash.

cosmic rain
exotic quiver
#

i'll give it a shot. thanks

exotic quiver
# cosmic rain If so, you could try breaking with a debugger. Might need to attach it to a proc...

now i was able to get unity to crash when attaching a debugger:

    Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================```

not quite helpful.
cosmic rain
exotic quiver
#

well this is the info from the editor.log from the crash. everything else is giving no further clues, just the stacktrace n loaded modules.

cosmic rain
exotic quiver
#

it pinpoints exactly to the SendWebRequest

cosmic rain
#

I see. What unity version are you using? Did you search online for similar issues?

exotic quiver
#

2022.3.17, upgraded from 2022.3.8 as there were similar ones in the unity bug tracker, but apparently all are marked as fixed within my version(s)

cosmic rain
exotic quiver
#

oh great idea! gimme a sec

crystal holly
#

anyone got advice for getting vscode working with editorconfig? mine appears to ignore it :\ (couldn't see a channel for questions about IDEs, apologies if this is in the wrong place)

mighty void
#

Hi someone could help me? I have a problem, i'm making a 2d procedural terrain with perlin noise

#

But i dont know how i can set the block levels, like how put the grass the dirt and that

#

Cause i dont wanna program It i wanna make It in a for statment

crystal holly
mighty void
crystal holly
#

It was a suggestion, not a question ๐Ÿ™‚

mighty void
crystal holly
mighty void
#

What I want to do is automate the process to be able to add elements to a list of blocks and be able to position them

empty elm
#

I have a class CustomButton and interface ButtonObserver { onClick() }
The button component needs a reference to the observer but I can't serialize it since its an interface. I could make ButtonObserver a serializable abstract class but that comes with other disadvantages. What are some work arounds?

rigid island
#

wouldn't custom button just fire event for button observer to listen to ?

empty elm
rigid island
#

something like this ?

public class CustomButton : MonoBehaviour
{
    public event Action OnClick;
    public void Clicked() => OnClick?.Invoke();
}
public class Listener : MonoBehaviour
{
    [SerializeField] CustomButton customButton;
    private void OnEnable() => customButton.OnClick += CustomButton_OnClick;
    private void OnDisable() => customButton.OnClick -= CustomButton_OnClick;
    private void CustomButton_OnClick() => Debug.Log("buttonClicked!");
}```
lunar lynx
#

is there a guarantee that materials using RenderTextures wait for RenderTextures to be ready before rendering the material?
for example: I have a Camera that renders to a RenderTexture. That RenderTexture is used in a material, and that material is applied to Model.

What is the order of the render in Unity? Does it go

  1. Camera renders to RenderTarget.
  2. RenderTarget applied as material input.
  3. Render Model with the material.

Or is it possible for the sequence to go:

  1. Render Model with the material (but RenderTarget input has not been updated yet)
  2. Camera renders to RenderTarget.
mighty void
#

Someone could guide me?

lean sail
# mighty void Someone could guide me?

you may wanna clarify further, because your question is seemingly just "i dont wanna use an if statement" which alone is a silly idea. what specifically is the issue with doing so?

quasi jewel
#

Have any of you guys tried or have an opinion on the free code camp C# course?

#

I'm taking it right now even though I've been using unity for a couple months and feel like it's great

mighty void
#

The terrain is not generated with a fixed height, but it is generated with a maximum height that cannot exceed

lean sail
mighty void
# lean sail i meant what specifically is the issue? like you say you dont wanna use an if st...

I don't find a way in which I can place the blocks in an order according to their properties of each one, for example, if the height of the column is 17 then place grass on that block and the following ones (randomly denyro of itself) I generated 4 blocks of earth and the rest are rock, I can't find the logic, it's hard for me to think logically sometimes, it would help if you could guide me, and I would like to do a foreach on the list I have of blocks because I feel like I can access all of their blocks. values, in the case of using if no, how could I adapt it to its infinite or changing values โ€‹โ€‹(from the list I mean)

lean sail
lean sail
mighty void
#

Ok

#

I have a list of blocks, it is not really defined, I have plans to create more blocks and add them to the list, and with the same script generate other worlds, distinguish

#

I'm not really sure how to replace the blocks using a for breaking down the properties, for example the value of the grass generation, its minimum value is 1, but if a mountain has a peak of height 17, how do I change that block 17 and I generate 3 blocks further down the ground or different levels of land depending on the column

mighty void
lean sail
#

or really just look into what minecraft does since this seems to be a clone

mighty void
#

It's something similar but in 2D

#

Like this

#

But when i try with a for always the The result is always that blocks like grass are placed at coordinate 0

#

and the land is generated in the same way following that pattern, how do I use the height of each column to generate the blocks in the correct way?

rigid island
mighty void
#

:T i take a photo beacuse i send in WhatsApp :T

spring creek
vale bridge
#

Accidentally stumbled upon the Enum type when I wanted to declare an enum, apparently there's two different "enums" depending on if you capitalize the e or not?

Enum vs enum what's the difference?

rigid island
#

just like string is String

vale bridge
#

I actually have no idea what the difference is

#

Ohhh

rigid island
vale bridge
#

so similar to the string thing enum is the C# alias for the original Enum class? Something like that?

rigid island
#

keyword for creation vs the actual implementation basically

vale bridge
#

Can I say that string and enum are both created for the purpose of easier "creation" of their original types

rigid island
#

in a way kinda

#

but they kinda serve bit different purposes

vale bridge
#

I see

lean sail
#

its just an alias

chilly surge
#

There is also a semantic difference, when you use string it explicitly means System.String, it can't be anything else; whereas if you use String, it could be System.String, it could be MyAwesomeProject.String, or any other class named String.

#

In practice this rarely ever matters, but it's just good to use string over String, it makes your intent very clear.

rigid island
#

also you can directly access string methods like with string.Parse
With enum the enum keyword is for creation , you can acces static methods with Enum class

#
var list = (Somethin[])Enum.GetValues(typeof(Somethin));//valid
var list = (Somethin[])enum.GetValues(typeof(Somethin));//nope```
edgy ether
#

so, is it possible to transfer a component and it's values from one gameobject to another via script?

#

ex: a polygon collider's values

lean sail
heady canopy
#

Hi, I downloaded for the first time and I can't open a new project

grave bloom
#

how do i set notification icon with unity mobile nofitication's unified API ? it is really driving me crazy

mossy snow
#

you might want to spend a little more time clicking around the documentation

spring basin
#

Hello had a doubt about an email I got.

#

Does this mean, I have to add levelplay to apps which serve Unity Ads exclusively as well?

sleek bough
#

@spring basin This is a code channel

spring basin
#

could you please redirect me to the channel where I can ask this question? Thank you

sleek bough
#

This is a support issue anyway. Create a ticket on website. Did you even try to look this up? People probably discussing it on a forum somewhere.

spring basin
#

didnt really find a thread on the forum for this specific one ._.

#

ill look again

sleek bough
spring basin
#

thank you

lean seal
#

hi, I wanted to make a thing so that when you click on the object it goes down some distance and I did it, but there is a problem
if the parent object is rotating and the child object goes down with update: transform.position = transform.up * -20 * Time.deltaTime; then everything works correctly
but if you try to do the same with a coroutine. then the object goes to the place where it would be if the parent object were not rotating

public float fallDistance = 100f; // The distance the image will fall
public float fallDuration = 0.5f; // The duration of the fall
private IEnumerator CustomAnimation()
{
    Vector3 originalPosiition = transform.position;
    Vector3 fallPosition = originalPosiition + (transform.up * (-fallDistance));

    float elapsedTime = 0;
    while (elapsedTime < fallDuration)
    {
        transform.position = Vector3.Lerp(originalPosiition, fallPosition, elapsedTime / fallDuration);
        elapsedTime += Time.deltaTime;
        yield return null;
    }
}

Maybe i do something wrong?

knotty sun
#

move your fallposition calculation inside the while, presumably the transform.up is changing due to the rotation

fervent furnace
#

transform.up will be changed if parent is rotating
and you use this in your "original" calculation

muted patrol
#

@vale wharf check your inbox!

vale bridge
#

Is this an accepetable/good way of setting up controls? I'm curious how people have set up controls before the new unity input system:
https://pastebin.com/4bmvHt0Q
https://pastebin.com/4zDeUjgE

slate imp
#

Hi, i've got a strange behaviour from unity :
in the following, the remove method is called by an event, and in the if(gameObject != null) Destroy(gameObject) i have an error of the object is already destroyed :

    /// <summary>
    /// Removes the word interactable
    /// </summary>
    private void Remove() {
        
        if (pairedWord != null) pairedWord.OnWordTouched -= PairedWordHandler;
        gameState.OnGameOver -= OnGameOver;
        if (gameObject != null) 
            Destroy(gameObject);
    }

the error :

MissingReferenceException: The object of type 'WordInteractable' 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.
WordInteractable.Remove () (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/WordInteractable.cs:46)
WordInteractable.OnGameOver (System.Object sender, System.EventArgs e) (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/WordInteractable.cs:51)
GameStateSO`1[T].GameOver () (at Assets/_Summer2024/Shared/Scripts/So/GameStateSO.cs:27)
knotty sun
maiden heath
#

is there a way to make unity search for a specific file name and use it to set a value?

#

i mean in my assets

slate imp
vale bridge
slate imp
slate imp
knotty sun
cosmic rain
slate imp
slate imp
#

the method is private

cosmic rain
knotty sun
slate imp
cosmic rain
slate imp
cosmic rain
#

I don't think regular C# delegate events throw an error like that.

slate imp
knotty sun
# slate imp i don't quite understand

if the event which calls OnGameOver belongs to WordInteractable then when you Destroy the gameobject you are also destroying the source of the event call

cosmic rain
slate imp
knotty sun
slate imp
# knotty sun It's like trying to remove the chair you are standing on if you get my meaning

yep got the meaning, i think i've got the source of the issue :

In the full log, at the begining we have line 34 WordInteractable that send an event to say he's touched, then destroy himself, but when he's destroyed, the player change and the health of the player goes to 0, which makes the gameOver and re-tries to Remove

MissingReferenceException: The object of type 'WordInteractable' 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.
WordInteractable.Remove () (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/WordInteractable.cs:46)
WordInteractable.OnGameOver (System.Object sender, System.EventArgs e) (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/WordInteractable.cs:53)
GameStateSO`1[T].GameOver () (at Assets/_Summer2024/Shared/Scripts/So/GameStateSO.cs:27)
WordSaber.GameModeManager.EndGame () (at Assets/_Summer2024/WordSaber/Scripts/GameModeManager/GameModeManager.cs:47)
WordSaber.SurvivalManager.EndGame () (at Assets/_Summer2024/WordSaber/Scripts/GameModeManager/SurvivalManager.cs:28)
WordSaber.SurvivalManager.WordHit (System.Object sender, System.Boolean isCorrectWord) (at Assets/_Summer2024/WordSaber/Scripts/GameModeManager/SurvivalManager.cs:37)
WordSaber.WordsManager.<Spawn>b__18_1 (System.Object sender, System.Boolean _) (at Assets/_Summer2024/WordSaber/Scripts/WordsManager.cs:102)
WordInteractable.WasHit (System.Boolean isRightHand) (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/WordInteractable.cs:34)
SaberInteraction.OnTriggerEnter (UnityEngine.Collider other) (at Assets/_Summer2024/WordSaber/Scripts/SaberInteractions/SaberInteraction.cs:12)
#

But i though having the if gameObject != null should prevent this issue

knotty sun
#

no, because gameobject is not null at that point

#

you need to move the Destroy(gameObject) back to the start of the call chain

#

Although if it is GameOver why even bother?

slate imp
knotty sun
#

no, I mean why bother destroying, a scene Load will clean up anyway

slate imp
slate imp
#

so they disapear when they are touched or the game is ended

mellow sigil
slate imp
#

i have a warning saying this is always != null

knotty sun
#

how can this be null and yet still be executing?

mellow sigil
#

I think what's happening is that the gameobject is destroyed but the method is called by an event so accessing gameObject throws the error inside this method instead of when calling the function

slate imp
mellow sigil
#

Unity objects override the null check so destroyed object == null

knotty sun
#

the problem is he is trying to Destroy the object which is executing the current code

mellow sigil
#

No, the problem is trying to execute the current code on a destroyed object

slate imp
#

events are strange

knotty sun
#

thet just means the Destroy never happens.
Use the debugger to check

mellow sigil
#

The object is already destroyed

lament mural
#

Hey guys! I'm currently running a spherecast to check if a position would be intersecting a collider if my player would teleport there. What I realised is that spherecast doesn't seem to detect a collider if it starts inside the collider. Is there a way around this?
I'm using a spherecast so that I know the player's body does fit in the area.

mellow sigil
lament mural
#

Thank you for your reply @mellow sigil! I also found Physics.OverlapSphere() which does essentially the same but it turns out that yours fits my needs better.

lean seal
gusty aurora
#

Is there a way to return a yield instruction ?

#

ie. if(bool) return "yield return null"
else return noyield ?

knotty sun
#

what would be the point of returning noyield. Just don't return

gusty aurora
#

I can't return nothing lol

knotty sun
#

so dont return at all

leaden ice
lean seal
gusty aurora
#

Doesn't work. It skips a frame no matter if true or false

public static IEnumerator CheckFixedTimeStep()
{
if (Time.inFixedTimeStep)
{
yield return null;
}
}

lean seal
#
public static IEnumerator CheckFixedTimeStep()
{
    if (Time.inFixedTimeStep)
    {
        yield return null;
    }
  yield return null;
}
#

u getting error bc if if skipped u r not retuning anything

#

so u need else with return or return after if

#

if im not wrong

knotty sun
gusty aurora
#

print(Time.frameCount);
yield return CheckFixedTimeStep();
print(Time.frameCount);

=> 101 then 102 even when from Update

knotty sun
gusty aurora
#

Doesn't work, exactly same issue as above

hexed pecan
gusty aurora
#

delaying the beginning of the coroutine for one frame if and ONLY if it was started from fixed update

knotty sun
gusty aurora
#

And now how to move that to a separate method ?

#

It's the one I posted on my very first message, try to move it to a separate method and you'll see its behaviour changes

leaden ice
leaden ice
maiden heath
#

why does OnTriggerExit2D not show up in intellisense

gusty aurora
leaden ice
cosmic rain
#

Shamed why? Is it against your religion or something?

#

Even if it is, it's your personal matter of wether to use it or not.
I say if it works for you why not.๐Ÿคทโ€โ™‚๏ธ
That being said, it might not always work for you, so learning the basics is still a must imho.

#

AI is still not at the level where it can write anything slightly complex for you. It can help you learn the concepts and write it on your own though.

abstract nimbus
#

has anyone bothered with calculating the distance between two points in any number of dimensions?

late lion
abstract nimbus
#

I tried this but something seems to be odd with some tests

    public class VectorN
    {
        public double[] dimensions;

        public VectorN(int dimensions)
        {
            this.dimensions = new double[dimensions];
        }
        public VectorN(double[] dimensions)
        {
            this.dimensions = dimensions;
        }

        public static double Distance(VectorN a, VectorN b)
        {
            if (a.dimensions.Length != b.dimensions.Length)
                throw new Exception("The vectors must have the same amount of dimensions!");

            double sum = 0;
            for (int i = 0; i < a.dimensions.Length; i++)
            {
                sum += Math.Pow(a.dimensions[i] - b.dimensions[i], 2);
            }

            return Math.Sqrt(sum);
        }
    }
heady iris
#

Geometry can behave in non-intuitive ways in higher dimensions.

#

For example, the volume ratio between hyperspheres and hypercubes crashes to near-zero

#

What's the problem that you are seeing?

abstract nimbus
#

I can't explain lol

heady iris
#

so you have a problem, but you can't articulate what the problem is...?

abstract nimbus
#

idk how to prove that my Distance function works either

#

well the problem is a long story ๐Ÿ˜›

cosmic rain
#

If it works for these 2, it likely works for any dimension.

heady iris
#

If your problem is that your distances feel "too long", consider that [0.5, 0.5] has a magnitude of 0.707, whilst [0.5]_10 (so, a 10-dimensional vector where every value is 0.5) has a magnitude of 1.58

abstract nimbus
#

I will compare Unitys 3D distance with my 3d distance then

heady iris
abstract nimbus
#

it does work for the 1st, 2nd and 3rd dimensions at least

#

maybe my problem isn't with the distance calculation then

heady iris
abstract nimbus
#

I'm mainly experimenting so if it sounds crazy you have been warned

#

this is an XOR gate in 2 dimensions. Instead of a traditional neural network. This method uses dimensions as inputs and the output is the total distance between the black dots position and all the white dots. The size of the circles reduces the distance

#

so I'm trying to achieve this in any amoutn of dimensions

heady iris
#

And what's the issue?

#

Is the distance larger than you expected?

abstract nimbus
#

the total distance seems to be always positive when I increase the dimensions

#

and it struggels to learn at higher dimensions

#

in this case I tried with 12 dimensions

heady iris
#

You have encountered the CURSE OF DIMENSIONALITY ๐Ÿ‘ป

abstract nimbus
#

lol

#

and I thought I came up with a really innovative way to make a neural network ๐Ÿ˜‚

heady iris
#

If you add dimensions but keep the number of points constant, your density falls off a cliff

heady iris
#

The volume of a high-dimensional hypersphere with radius 1 is way smaller than the volume of a hypercube that's 2 units across

abstract nimbus
#

๐Ÿค”

heady iris
#

It is non-intuitive, because you're trying to think about the only thing you can really comprehend: a 2-sphere inside a 3-cube

#

(so, a sphere in a cube)

cosmic rain
abstract nimbus
#

it's just a mutation algorithm

heady iris
#

whoops, wrong reply

heady iris
abstract nimbus
heady iris
#

If you keep cranking up the dimensionality, then points randomly positioned inside of a hypercube get further and further apart.

abstract nimbus
#

but they are not cubes tho? They are spheres cuz they have a radius

heady iris
cosmic rain
#

Isn't that what neural networks do already with back propagation?

abstract nimbus
heady iris
#

but there's no rule that says you can't just randomly wiggle around

#

or that dogs can't play basketball

cosmic rain
#

Yeah. What I'm trying to say is that the simpler options were probably already explored by many researchers before.

abstract nimbus
#

are you saying that:
a sphere in higher dimensions with radius x is bigger than a sphere in lower dimensions with radius x?

#

by size I mean distance between the spheres origo to its edge

heady iris
#

In fact: no!

#

They peak at a certain point and then drop to near-zero

#

At n=12, you're on the downslope

#

a edge-length-2 hypercube has a volume of 2^n, whilst a radius-1 hypersphere (which fits neatly into the cube)'s volume has a factorial in the denominator

#

which we call a "Big Oof"

abstract nimbus
#

wdym by factorial in the denominator

heady iris
abstract nimbus
#

I know what factorial is but I'm confused in this case

heady iris
#

gamma extends the factorial function to non-integers

#

this function crashes to zero very quickly

#

High-dimensionality spheres have basically zero volume.

abstract nimbus
#

so I just increase the radius for higher dimensions

heady iris
#

you have to increase it a lot

maiden heath
#

how do i get rid of the box icon? im using aseprite importer

heady iris
#

If you unpack the prefab, it becomes a normal object

#

(which, of course, breaks the prefab connection)

maiden heath
heady iris
#

Why do you want to do this?

maiden heath
heady iris
#

it explains the exact problem you're encountering

heady iris
maiden heath
# heady iris ...no?

oh that was the impression i got.. i thought the box icon acted like a zip folder

heady iris
heady iris
heady iris
#

this is more obvious with 3D models -- if you add another object in blender, the unpacked prefabs won't get the new object

abstract nimbus
heady iris
#

it just references an Animator Controller and some sprite assets

#

in that case, it doesn't matter if it's unpacked or not

abstract nimbus
#

but I also just noticed that my algorithm struggles to learn the more "neurons" it has so increasing the dimensions means increasing the neurons

heady iris
#

"WeaponManagerController" is a mouthful

#

both "manager" and "controller" imply that they operate on many objects (especially "manager")

heady iris
#

"GunPickupAndThrow" 's job is to pick up and throw weapons. The name should indicate this.

#

I remember suggesting "WeaponHandler" for that reason

abstract nimbus
#

why am I not allowed to say "hmm"?

heady iris
#

the server blocks a lot of no-content messages

abstract nimbus
#

lol

heady iris
#

I do get whacked by the "hmm" filter from time to time

abstract nimbus
#

not working either ๐Ÿ˜‚

#

it's too smart

heady iris
#

Those points are positioned on the corners of the 3-cube

abstract nimbus
#

so they are in range -1 to 1

heady iris
#

The distance from the n-cube's corners to the surface of the [n-1]-sphere gets larger and larger as you add dimensions

abstract nimbus
#

[n-1]-sphere meaning the edge of the sphere?

heady iris
#

a 2-sphere is the 3D sphere you are familiar with

#

hence n-1 when comparing it to an n-cube

#

a 3-cube is a 3D cube

#

go figure (:

heady iris
abstract nimbus
#

man time to explode my brain

#

@heady iris are you talking about this distance?

abstract nimbus
#

so that increases in higher dimensions

heady iris
#

That distance grows as you add more dimensions.

abstract nimbus
#

yeah it makes sense when you compare the distance in 2d vs 3d

heady iris
#

The part of a sphere closest to a corner will have coordinates that all have the same magnitude (either positive or negative)

#

adding more dimensions means that more numbers have to have a sum-of-squares value of 1, so the value of each number has to go down

abstract nimbus
#

so should I do something like radius = Pow(radius, dimensions) ๐Ÿ˜‚

heady iris
#

sqrt(d * x^2) = 1

therefore, x trends to zero as d increases

heady iris
plush musk
#

Hiho, I'm trying on a PropertyDrawer for RectOffset that is used for HorizontalLayout padding.
I got it to draw like I want it to, but changes to the fields are not updated to the object. Any idea?

code: https://gdl.space/eqamopuwoy.cs

heady iris
#

link doesn't work

abstract nimbus
heady iris
wise pumice
#

Hey guys, I was following along to a tutorial, but I'm having a couple of weird bugs.

The code is here - https://pastecode.io/s/3xjbhpp2

I'm having an issue where my AI like, stutters or something when arriving to his destination and I can't figure out why

I took a little gyazo video to show it and will list below.

One other thing I am having a problem with is, where we do this section in the synchronize

``bool shouldMove = Velocity.magnitude > 0.5f && Agent.remainingDistance > Agent.stoppingDistance;

    Animator.SetBool("move", shouldMove);
    Animator.SetFloat("locomotion", Velocity.Magnitude);``

My AI just starts sort of teleporting a bunch, I've fixed it for now by changing the last line to
shouldMove ? 1 : 0 (In the animator, the locomotion number was rapidly changing and was showing 1.5 at times, which shouldn't happen because we are getting magnitude?)

1st video - https://gyazo.com/a71b835c6f4b86fc81c64c8457e1362d
2nd video - https://gyazo.com/56e9d231184dcc130ade2735f9acd9c7

abstract nimbus
#

btw one funny thing I did was sending my code files to GPT and asking it how I would train it and then it gave me a Gradient Decent algorithm that worked with some tweaks here and there lol

#

so now I can use that instead of mutation

heady iris
#

If your animations contain root motion, they could be causing you to move around suddenly

wise pumice
plush musk
heady iris
#

I'm not sure what the correct move is here, actually

plush musk
#

okay, thanks

heady iris
#

perhaps you wanted to normalize it?

#

I'd get rid of the smoothing, too, so that it's easier to spot the issue

#

by the way, you can just use transform.InverseTransformVector to turn a world-space vector into a local-space vector

wise pumice
#

Still trying to come to grasps with it

abstract nimbus
#

@heady iris another way to solve the issue is by making the space more dense. Maybe that's what you tried to say before?

        public static SpatialNeuron GenerateRandomNeuron(int dimensions)
        {
            double radius = NeuralNetwork.GenerateRandomNumber(-1, 1);
            var neuron = new SpatialNeuron(new VectorN(dimensions), radius);
            for (int i = 0; i < dimensions; i++)
                neuron.position.dimensions[i] = NeuralNetwork.GenerateRandomNumber(-0.001, 0.001);

            return neuron;
        }

this is how I generate those spheres in x dimensional space. I also gave some spheres negative radius

#

I hardcoded 0.001 to test with 12 dimensions

heady iris
#

but the Vector method isn't quite appropriate here

#

this should be a direction

#

You shouldn't move twice as fast when you're twice as far away

#

So we should:

  • normalize the vector
  • use transform.InverseTransformDirection
#
Vector3 worldSpaceVector = /* something */
Vector3 worldSpaceDirection = worldSpaceVector.normalized;
Vector3 localSpaceDirection = transform.InverseTransformDirection(worldSpaceDirection);
#

The Direction method doesn't change the length of the vector you give it

#

the Vector method does (if you are scaled)

#

A normalized vector has a length of 1.

wise pumice
heady iris
#

you have a comment in your code that indicates exactly where you convert from world to local space

#

(:

#

note that after you do this, you'll still need to create a new Vector2

#
Vector3 localDirection = /* ... */
Vector2 deltaPosition = new Vector2(localDirection.x, localDirection.z);
#

(local Y is up-down)

#

X is right-left and Z is forward-backward

#

which is why you were doing this:

        float dx = Vector3.Dot(transform.right, worldDeltaPosition);
        float dy = Vector3.Dot(transform.forward, worldDeltaPosition);
        Vector2 deltaPosition = new Vector2(dx, dy);
maiden heath
#

i can use scriptable objects to make a dialogue system right? because im not sure how they work

heady iris
#

that implies your bullet points in its right direction

#

The LookRotation code would work for a bullet that points in its up direction

#

I've had a similar issue in 3D

#

If you shoot bullets from the gun's actual barrel, then you have to rotate the gun to point at what the crosshair is hovering over.

#

It's inconsistent up close, actually

#

That's where you need a very large rotation

#

At long ranges, it barely matters

wise pumice
# heady iris you have a comment in your code that indicates exactly where you convert from wo...

Gotcha, thanks for that ๐Ÿ™‚
One more thing which I'm not sure if you can help me with.

I like the random wander that the **DoMoveToRandomPoint" does, but I can't actually understand it at all. And currently, the AI will wander either short or massive distances on my plane.

I'd like to change it to be within a certain radius that it generates a point instead, but this one is completely different from the usual way I see

heady iris
#

The nav mesh is a...mesh. It's made of triangles.

#

This code is actually kind of wrong. It's picking a random vertex, then picking a vertex that's either one ahead or one behind it

#

The idea is to pick a random triangle and pick a random point inside of it

#

But this might pick a vertex from one triangle and a vertex from another triangle

#

which could be really far apart (or even give you a point that's out-of-bounds)

#

When implemented correctly, this code still doesn't work that well

wise pumice
#

Makes sense so far yeah

heady iris
#

It's biased towards denser parts of the mesh

#

you can one many triangles for a complex area and very few triangles for a simple area

#

An easy way to sample a random point would be to use NavMesh.SamplePosition

#

In fact, the example is for picking a random point on the nav mesh!

#
Vector3 randomPoint = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
{
    result = hit.position;
    return true;
}
#

This picks a random point within range meters, then tries to snap to the nav mesh (moving at most 1 meter)

#

The larger the radius, the more expensive it gets to do the query

wise pumice
#

Okay, so just working out how to edit it to be like that atm, how exactly would center be defined in this case though?

#

Oh nvm actually lol

heady iris
#

you'd start from your current position

wise pumice
#

I was reading your section above and not the link

#

So I was missing some clues

heady iris
#

I have methods that look like this:

public IEnumerable<Foo> GetFoos() {
  yield return whatever;
  // ...
}

I want to add methods that look like this:

public void FillFoos(List<Foo> list) {
  list.Add(whatever);
  // ...
}

The latter will be used in situations where I can just fill up a list and then iterate over that, thus avoiding a bunch of allocations.

I'd rather not write the same logic twice. Is there a better way to avoid repeating myself than to replace the first method with this?

public IEnumerable<Foo> GetFoos() {
  var list = ListPool<Foo>.Get();
  FillFoos(list);
  foreach (var foo in list) {
    yield return foo;
  }
  ListPool<Foo>.Release(list);
}
quasi edge
#

Does anyone know how to edit the position of a textmesh pro gameobject in script?
So far i've tried:

myText.getComponent<rectTransform>().position += new Vector3(0, 1 0);
// and 
myText.transform.position += new Vector3(0, 1 0)

Both of them don't cause an error but they don't work

heady iris
#

Both of these are doing the same thing: myText.transform gives you the RectTransform

#

If this is on a "Screen Space - Overlay" canvas, then 1 unit might only be one pixel on your screen

#

Did you check the object's inspector to see if it's moving?

quasi edge
#

thanks

#

it didn't occur to me that it would be in pixels instead of units

heady iris
#

well, those are roughly equivalent here

quasi edge
#

I was using the same constant I had used for other gameobjects so thats why it barely moved

heady iris
#

you might have noticed that an overlay canvas looks huge in the scene view

#

Assuming there's no scaling going on, your position on an overlay canvas is your position on the screen, measured in pixels

#

so if you're 500 pixels from the left, your world position X is 500

quasi edge
#

oh i see

#

so in the scene view 1 unit is actually 1 piexel

#

that makes sense

small oxide
#

What is the best way to optimize the performance of a game? (cullings)
I tried with chunks, but I couldn't do anything

spring creek
small oxide
spring creek
small oxide
#

What do you mean with profile?

dusk apex
#

The profiler

small oxide
spring creek
# small oxide

You should look up a guide on how to use it. The hierarchy view is going to be the most helpful

mighty void
#

I am creating a procedural panera terrain using perlin noise, the problem I have is that I want the terrain to be generated in capable, there is no maximum height at which the mountains are generated, but there is a height which it cannot exceed, the problem I have a list with blocks which I will add blocks as I create them, the problem is that I don't know how to ensure that the blocks are generated correctly, because in this way blocks are generated on top of each other, any questions or comment or help would help me

grim gyro
#

Has anyone encountered this error?๐Ÿ˜ถโ€๐ŸŒซ๏ธ
The funny thing is that it occurs only in the web build. It doesn't happen on other platforms or in the editor

gusty aurora
# heady iris

Waow, I studied the full demonstration of this formula last year, didn't think it would ever be useful ๐Ÿ˜ฎ

maiden stone
#

Hello, I heard some people saying that scriptable objects can be problematic in some cases. Does this mean I shouldn't use them for my game? and in what instances can it be problematic?
One more question. Im trying to make an audio handler. For this, should I use a scriptable object or singleton?

heady iris
#

that's incredibly vague

#

you can cause problems for yourself if you try to store data in scriptable object assets, though

#

If you load a new scene and nothing is referencing the object, it gets unloaded

#

any changes you made to it will be gone the next time it loads

#

I use ScriptableObjects (almost) entirely for read-only data

late lion
#

When you think about it like that, it sounds silly to say you shouldn't use ScriptableObject. It's the only way to create custom asset types, which can be very useful.

maiden stone
#

Okay, so then would it be better to use a singleton rather than a scriptable object to store / hold audio's temporarily for my audio handler?

late lion
#

Some of Unity's built-in asset types, like Material, are designed to be mutable (for better or for worse). It's not terrible, but can be confusing.

late lion
maiden stone
#

My apologies. It was meant to be store / hold.

heady iris
heady iris
#

What will you be doing with this object/singleton?

maiden stone
#

I am trying to create a system where I can use to play audio. This audio will be created as its own instance in game and put at a specific vector 3, based on where the method is called from. It can be called by any script. Audio, as well can play in mono instead of stereo. (Probably by either changing some settings or just setting the audio position constantly to the player position)

#

I'm thinking, I could have an array, or some data holding to store my audio/music (currently I have music being held in a scriptable object, and being sectioned in a property drawer in a specific order that it is supposed to play.) I'm trying to make a system, in which can handle multiple sounds, as well as music. I already have the script for reading these scriptable objects nearly created. When read, returns a sound file, which I would then like to import into my playaudo() method, and in turn, play the audio with any given parameters

#

My question; should I use a singleton, scriptable object, or script connected to a game object to handle this?

#

I hope this clears things up?

#

(I very well could be over thinking this)

frozen ridge
#

i'm trying to implement a building placement system,

If i have BuildingSO and Building classes, BuildingSO holds name, prefab, cost and Building has BuildingSO, does this create a circular dependency since BuildingSO needs the prefab and Building is on the prefab and needs BuildingSO

rigid island
frozen ridge
#

buildingSO has prefab, on the prefab there is Building class

#

i'm confused as well

spring creek
#

It should be on an empty just for placing, then you instantiate the specific building prefab when placed

frozen ridge
#

but why, shouldn't every building has a building class

#

oh wait

#

should i create an empty parent and make the prefab its child?

#

and then the parent will have building class

spring creek
#

That sounds reasonable

#

The prefab for the SPECIFIC building should just be the model and any specific behaviour that is unique to it

#

The parent you want to be generic. Building would be on EVERY building, so it belongs there with the parent

frozen ridge
#

let me think i don't think i understand

#

is there a better way to do it? I feel like i'm creating a problem that shouldn't exist

rigid island
#

isnt the prefab just a visual? whats it got to do with building class

frozen ridge
#

But i need the prefab to instantiate a building

rigid island
#

don't you have something like this

public class BuildingSO : ScriptableObject
{
    public string buildingName;
    public Transform visualPrefab;
    public int cost;
}```
frozen ridge
#

When initiating the building itself, i get the game object from the SO

rigid island
frozen ridge
#

yeah just a GameObject instead of Transform

rigid island
#

alright. so I fail to see anything circular about this

#

BuildingSO has no idea about the Building class

#

in other words you're probably worrying about the wrong thing

frozen ridge
#

yeah i think i'm a little dumb tonight sorry

timid brook
#

I can't figure out why sticking to planets doesn't work...

I'm trying to make a outer wilds inspired character controller that walks on planets like in Mario Galaxy.
Everything was working fine up until I started rotating the planet along it's axis. The player being parented to the planet moves alongside it, however now the player doesn't rotate anymore, how can I fix this?

#

This is the code that attracts the player to the planet, what I think the problem is, is that body.rotation isn't getting set when the planet is rotating.

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

public class GravityAttractor : MonoBehaviour
{
    public float gravity = -9.8f;

    private Quaternion targetRotation;
    private float rotationSpeed = 5f;

    public void Attract(Rigidbody body) 
    {
        Vector3 gravityUp = (body.position - transform.position).normalized;
        Vector3 localUp = body.transform.up;
        body.AddForce(gravityUp * gravity);

        targetRotation = Quaternion.FromToRotation(body.transform.up, gravityUp) * body.rotation;
        if (body.constraints != RigidbodyConstraints.FreezeRotation) return;

        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, Time.deltaTime * rotationSpeed);
    }  
}
frozen ridge
#

does the player fall over when trying to rotate left or right?

timid brook
#

no

#

I have setup constraints

#

It's weird, when the planet isn't rotating it works fine, but after i start rotating it around it's axis... It's like body.rotation = Quaternion.Slerp(body.rotation, targetRotation, Time.deltaTime * rotationSpeed); this doesn't set the rotation

#

and i have tried without the slerp aswell, to no awail

frozen ridge
#

i think its either that or your targetRotation gets messed up because the planet is rotating

#

Since the player is parented to the planet its rotation or other values could be different from what you expect

timid brook
#

i think so too, but i don't know how to fix it

#

so i added a test float that increases after time to test what really happens```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GravityAttractor : MonoBehaviour
{
public float gravity = -9.8f;

private Quaternion targetRotation;
private float rotationSpeed = 5f;
float test = 0;

public void Attract(Rigidbody body) 
{
    Vector3 gravityUp = (body.position - transform.position).normalized;
    Vector3 localUp = body.transform.up;
    body.AddForce(gravityUp * gravity);


    targetRotation = Quaternion.FromToRotation(body.transform.up, gravityUp) * body.transform.rotation;
    Debug.Log(targetRotation);
    if (body.constraints != RigidbodyConstraints.FreezeRotation) return;

    //body.MoveRotation(Quaternion.Slerp(body.rotation, targetRotation, Time.deltaTime * rotationSpeed));

    test += Time.deltaTime;
    body.rotation = Quaternion.Euler(new Vector3(0,test));

}  

}

languid hound
#

Does anyone see something wrong with this?

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

public class CollisionTest : MonoBehaviour
{
    public Transform target;
    public Vector3 lastPos;
    public float sphereScale;
    public LayerMask layersToCollideWith;

    public void Update()
    {
        transform.position = target.position;

        if (PathCheck(out RaycastHit hitInfo))
        {
            Debug.Log("ok");
            transform.position = hitInfo.point + hitInfo.normal * sphereScale;
        }

        lastPos = transform.position;
    }

    public bool PathCheck(out RaycastHit hitInfo)
    {
        if (Physics.SphereCast(lastPos, sphereScale, (transform.position - lastPos).normalized, out hitInfo, (transform.position - lastPos).magnitude, layersToCollideWith))
        {
            return true;
        }

        return false;
    }
}

I'm trying to sweep from the last to the current position to detect if it's penetrating something. Just as a test I'm trying to push something out

timid brook
timid brook
hexed pecan
languid hound
languid hound
hexed pecan
#

Actually you have this:cs transform.position = hitInfo.point + hitInfo.normal * sphereScale;
Depending on the behaviour you are after, you might want something like:cs transform.position += hitInfo.distance * directionNormalized;

#

Your current way of doing it kind of pushes it out in the normal's direction

#

Which may end up being further than you expected

#

If I'm thinking clear right now ๐Ÿค”

languid hound
#

Yeah the idea is it goes to the point it hit and then gets offset by the hit normal by the sphere's size which should in theory push it out completely in the right direction

#

Okay now I'm confused wtf

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

public class CollisionTest : MonoBehaviour
{
    public Transform target;
    public Vector3 lastPos;
    public float sphereScale;
    public LayerMask layersToCollideWith;

    public void Update()
    {
        if (Physics.SphereCast(transform.position, sphereScale, transform.right, out RaycastHit hitInfo, sphereScale, layersToCollideWith))
        {
            Debug.Log("!!!");
        }

        Debug.DrawRay(transform.position, transform.right, Color.yellow);
    }
}

I tried rewriting it from the start but for some reason it's saying that it hits the cube but only when it's further than the sphereScale (a unit away than it should be able to reach)

simple egret
#

It's normal, you're passing the scale (radius) into the distance parameter. Think of sphere cast as a thicker raycast, it still has a distance. The cast extends sphereScale units towards the right

languid hound
#

I'm not though

simple egret
#

maxDistance param

languid hound
#

Wait

simple egret
#

Consider using CheckSphere() if you don't need info on what you hit (just whether you hit or not), or OverlapSphere() if you do

languid hound
#

I need precise information on the rayhit which OverlapSphere can't give afaik

#

I'm still confused because this is using OverlapSphere as maxdistance
Even when the ray intersects it just doesn't log until it doesn't intersect

simple egret
#

Switch to 3D view, make sure the object isn't rotated around Y. Seems like it is, the yellow debug line is shorter than 1 unit from this perspective

#

Also temporarily get rid of the layer mask parameter to rule out a bad mask

languid hound
#

Even without the layermask param it still doesn't log until the line stops intersecting

#

Sorry wireframe was the clearest way to show this to me. This is a shaded view

hexed pecan
#

Your line is 1 unit long, it doesn't correspond to the spherecast. It only shows the direction, not length

languid hound
#

But sphereScale is also only 1

hexed pecan
#

So is it intentional that you spherecast with the sphere's radius as the max distance?

heady iris
#

Doesn't the spherecast ignore any colliders it starts out inside of?

hexed pecan
#

Yes

heady iris
#

Also, you're using a new enough version of the editor to turn visualize queries with the physics debugger

#

That may be illustrative.

languid hound
#

Ooh I haven't heard about that

hexed pecan
#

If the radius is 1 then it definitely starts inside that box

languid hound
hexed pecan
languid hound
#

Yeah that's why I moved it

languid hound
#

I'll just clean some of this up and then mention what was wronf

#

Okay yeah no the only issue I had was that sphereScale needed to be divided by two

#

I thought a SphereCast with a radius of 1 would be the same as a sphere in unity

heady iris
#

presumably you mixed up your diameter and your radius

languid hound
#

Yep rip lol

heady iris
#

yeah, unity spheres and cubes have diameters of 1

#

(well, cubes have edge lengths, not diameters, but same idea)

frozen ridge
#

How would you guys go about a building placement system, no matter what I think I can't imagine a way that I dont use a manager. Do you guys think its bad practice to use managers

heady iris
#

"managers" are perfectly fine

#

you're obviously going to have something that's in charge of how buildings are getting placed

frozen ridge
#

It's just that whatever I read they make so much emphasis on encapsulation, I feel like I break it when I use a manager instead of handling it in the object, but as you say how am I even supposed to place buildings without a manager

late lion
heady iris
#

Exactly.

frozen ridge
#

But I do access the internal state, at the very least I set the building's state to placed if I was able to place the building

heady iris
#

You'd tell the building that it got placed down.

#

you're asking "how do I write methods?" at this point :p

frozen ridge
#

I know what I ask feels like a basic and fundamental knowledge and maybe it isn't even that important but I guess it's better that I ask lol

heady iris
frozen ridge
#

I feel like I can implement complicated things reasonably well but I have problems when I try to use them together, like I can implement pathfinding algorithms pretty well and modify them however I like but when I try to come up with a system that can move units using different pathfinding algorithms and keeping it decoupled I have problems

frozen ridge
shut pagoda
#

Could anyone help me make a roll mechanic (like, roll a few units in a direction with editable stats and the roll decreases your collision by a bit)? I tried making it myself, looking for it online even using chatGPT but I can't for the love of god make it work (2D)
this is my current code https://gdl.space/eguqutipav.cs

wispy creek
#

Good night, an error occurred with the player movement, the player flies with/among the camera orientation, i will be sending all the scripts and relevant photos below:

#

Player Scripts:

leaden ice
#

that doesn't seem right

wispy creek
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    public Transform orientation;

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    void FixedUpdate()
    {
        Move();
    }   

    void Move()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        Vector3 moveDirection = transform.right * moveX + transform.forward * moveZ;
        rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
    }
}
wispy creek
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{

    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        //get mouse input
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //rotate cam and orientation
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, xRotation, 0);
    }

}
leaden ice
#

so of course when you move forward it will go in the air

#

when you're facing in the air

wispy creek
#

how am i solving it?

leaden ice
#

Your code looks like it's intended for a first person game

wispy creek
#

do i create a child "Player Camera" for "Player" with the camcontroller??

leaden ice
#

you're making a third person game

#

that script is not suitable at all

wispy creek
leaden ice
#

don't do that

wispy creek
leaden ice
#

your script should be movingt the camera

#

not rotating the player

wispy creek
wispy creek
wispy creek
#

now the camera doesn't follow the mouse

wispy creek
leaden ice
#

You can write one

wispy creek
mighty void
#

Someone could help me with a terrain generation?

hexed pecan
mighty void
#

But when i try this happens

hexed pecan
#

You should probably check if(y < localY && y > localY - thickness)

#

Where thickness is how many blocks the layer should be in the Y dimension

#

If you want something like in the first screenshot, that is

mighty void
#

And in that way i can make the correct terrain? I'm going to try

#

And I have another question,maybe i have to try to make first the foreach and inside make the for (int y) ?

hexed pecan
#

What is BlockData? Is it one vertical slice of the terrain?

#

Or one block?

#

In any case you seem to be a lot of unnecessary iteration here

#

For every cell you check every blockdata?

#

Maybe the blocks should be in a 2D array, or they should know their own position in the terrain

#

You could simplify the loops a lot

mighty void
#

Some bool values

hexed pecan
#

You are currently creating a block for every blockdata

#

Maybe associate a depth value for each blockdata if you want like different types on different layers

mighty void
hexed pecan
#

Yeah, maybe something like if(y > localY - data.maxDepth && y < localY - data.minDepth)

#

Where min/maxDepth are the depth or distance from the ground level

mighty void
hexed pecan
#

That's the point, you add different depth values to different BlockDatas

mighty void
#

I dont have a fixed listo of blocks

#

And how put in? Like i am doing in the method createblock?

hexed pecan
#

Replacing the current if(y < localY) is the idea

#

This is the simplest way I can think of - there are improved alternatives

mighty void
#

Look

mild goblet
#

question to the hive mind. Has anyone created a movement/collision detection system without physics (with the intention of better performance) ?

spring creek
leaden ice
#

but uh - sure I've done lots of grid based games and stuff that didn't involve the physics engine

shell scarab
#

How do I wait for a list request to finish if I can't use coroutines in the unity editor :(

#

they could have at least made it have an event thats called when finishing...

somber nacelle
shell scarab
#

i guess, it feels clunky that I have to install a package to wait for something asynchronously in their base API.

somber nacelle
#

i assume they are referring to this

rancid frost
#

Any ideas on how to represent this in unity?

A standard 2d array wont work due to the values(the biomes) not being designated points
I was thinking of creating a Bounds and having the biomes contained within said bounds.
Any other ideas?

vivid halo
# rancid frost Any ideas on how to represent this in unity? A standard 2d array wont work due ...

Piecewise functions might be a suitable yet inelegant solution.

if (temp <= -5) biome = Biomes.Tundra;`
if (temp <= -1)
{
  if (annualPercipitation < 5) biome = Biomes.Desert;
  else if (annualPercipitation < 20) biome = Biomes.TemperateShrubland;
  else if (annualPercipitation < 130) biome = Biomes.BorealForest;
  else if (annualPercipitation < 150) biome = Biomes.Tundra;
}
// This is probably neater with switch statements.
#

Pair it with some unit tests that test the diagram thoroughly and you can be sure it is working nearly as intended. If you can access the source data methodology, you might be able to find functions that represent the outputs, but it's not trivial to determine the functions and try to create an elegant (x, y) => biome mapping just based on the image alone.

#

I am working on a CameraController that has met requirements up until now: https://pastebin.com/H9M98ybh

The issue is that the current implementation does not work when the player is parented to another object, such as a rotating room, because the _currentYaw and _currentPitch private variables are not compatible with being rotated from an external source, and I am unsure how to approach implementation or refactoring, specifically regarding how to rotate the camera swivel externally in a way that is compatible with being externally rotated.

wooden lintel
#

i have a building that can be upgraded to a much bigger, nicer looking building. so i'm trying to bake the lighting with the upgraded building enabled and the original building disabled. then i make duplicates of the lightmap textures and isolate them in a unique folder and bake again with the opposite, upgraded building off and original building on.
when the player upgrades the building it's supposed to switch from the original building lightmaps to the upgraded building lightmaps. but for some reason the upgraded building lightmaps don't look like how it does when i bake the scene with it enabled.
i've been using chatgpt to help me figure out how to do it in the first place but regardless of cgpt's help i can't figure out what's happening. everything seems to work and be linked correctly when the building is upgraded but it just doesn't look like how it should.
how can i troubleshoot this or is there a better way to accomplish what i'm doing? also I'll link the code i'm using

#

oh and all my lights are set to Mixed mode and I'm baking with Subtractive mode

pastel patio
#

Hi guys, anyone know how to accurately get whether something is exposed? Even just a little bit, but I need to know whether they're completely behind cover

#

I need it for my 2d game where opponents behind objects will be hidden in network

#

May be a bit inaccurate in terms of opponents still being detectable a bit out of range, but it'd be bad if they're undetectable within view

fleet gorge
#

raycastall

#

sort the raycastall array based on distance, foreach object in the raycast, if the object is cover break the loop

#

but if it does hit an entity then damage them

gaunt holly
#

Hey, someone know how to make roads on Terrain like roads of GTA please ? Itโ€™s a texture who add ? or other ? thank you ping me please !

fleet gorge
#

roads on terrain?

#

using unity's in built terrain system? the most you can do in unity built in terrain system is paint on textures

#

youll need to use the 3d models of your road

#

@gaunt holly

pastel patio
fleet gorge
#

recently i was thinking about how to calculate wallbang

pastel patio
#

Or use the Out parameter to get info on that what's been hit

fleet gorge
#

in competitive tac shooters bullets can penetrate walls

#

im thinking about how to calculate that

pastel patio
#

Dot product

#

At least, if the condition is based on the angle your bullet has hit the wall with

#

However what I was asking is essentially if any point of an opponent is not obstructed

#

In my case specifically, can say that I wanna know if the target is inside the 2dlight cast by the player

#

However light doesn't have this function

knotty sun
pastel patio
pastel patio
#

xD But box cast all means all targets in the boxcast's path

knotty sun
#

yes, which is what you want is it not?

pastel patio
#

I mean, I suspect that it does not account for obstruction

knotty sun
#

then it is a simple bounds check to see what is obsuring what

pastel patio
#

Instead gives all the box cast results as if the rest doesn't exist

pastel patio
knotty sun
#

colliders have a bounds property. I suggest you go and read the Bounds docs

pastel patio
#

Haha well, apparent this bounds system is straight

#

Basically like taking the min and max of it

#

While the calculation in this case includes opponents being at 45 deg direction from you etc

maiden heath
#

is there a way to code my own node based dialogue system graph thingy?

fleet gorge
#

yes its possible, lots of work but many companies have it already

#

theres a few tutorials on it actually

#

first video i found on it

maiden heath
#

this seems really cool

#

easier than having a shit ton of if statements for my dialogue

fleet gorge
#

for myself i was lazy to do the whole thing so instead I used SOs

#

QuestManager can hold a selectedQuest.
Quest has a list of Objectives.
Objectives include Dialogue, Location(go to an area to advance), Interact, Puzzle etc

to start you can create a Quest, and add to the list of objectives within the quest. create a Dialogue scriptable object and drag it into the list of objectives. in the Dialogue scriptable object, you can add the lines that you want in a unity list.

#

I realised that its not very flexible though so I might combine both solutions eventually

magic harness
#

Hello guys, im having trouble with my game which uses mouse click to move, where the clicks pass through the UI. i tried using IsPointerOverGameObject on my floor(which has a NavMesh) but it returns true even if it is not over any Ui Object. Debugging raycast its really only catching the plane.

Can anyone help?

slate imp
#

Hi there, I've been making a game in VR, I'm looking for around 60 fps for a good experience, but as you see it's around 45, the part to look is in the center, on the left is when i was in a menu and on the right i was looking at the sky.

I have two main questions :

  • What is PlayerEndOfFrame that take some time in the next frame
  • What is Gfx.WaitForRenderThread that take a Huge time

Well, i know what globaly is WaitForRenderThread, but i dont know how to have a better profiling of this, neither to how to reduce the WaitForRenderThread

dry violet
#

It seems to me that it is because of the vsync that the headset has, reducing the render load will possibly improve it

cosmic rain
maiden heath
#

is graphview api deprecated?

cosmic rain
slate imp
cosmic rain
slate imp
cosmic rain
#

You could try looking at the GPU module if it works on your hardware

slate imp
#

i dont know how its work

dry violet
#

If you do the build in the glasses, does it also happen? it could be because of the connection

cosmic rain
#

The profiler has different modules. On your screenshot you have the CPU and rendering modules open. You can add and enable other, like the GPU one.

daring cove
#

Hey,

I need help with presenting the players joystick input as a point in a circle.

The joystick input is a Vector3. (pitch, yaw, roll)

I need to translate the input in the circle so that
When yaw is 100%
the point is at the right of the circle.
When pitch is 100%
the point is at bottom of the circle.
When roll is 100%
the point is in a diagonal position on the circle.

I have solved for x and y position.

point.x = root.x + joystickInput.x * circleRadius;
point.y = root.y + joystickInput.y * circleRadius;

the input axis can be negative, but always between -1 and 1.
the point is in 2D space.

The zero position would be the middle of the circle

gaunt holly
dry violet
#

3d model

slate imp
gaunt holly
daring cove
#

3d model interpolated with a spline is how they did it in GTA I think. In my own experience making roads by placing models manually is the pain of a lifetime. So look in to ways of automatically making this process.

#

There are most likely great tools on the asset store for this

dry violet
#

yes like a kit, There are addons in blender to make roads

gaunt holly
#

okay thank you Predator and Sami L

#

do you have video to help me about this ??

cosmic rain
cosmic rain
slate imp
cosmic rain
slate imp
daring cove
dry violet
# gaunt holly do you have video to help me about this ??

My procedural Road Generator geometry nodes that make creating road much easier and faster.
Software requirement: Blender version 3.5 or higher.
Suitable for Cycles and Eevee real-time render.

You can get this geometry nodes file for free at:
Blender Market: https://blendermarket.com/products/procedural-road-generator-geometry-nodes/?ref=1193

...

โ–ถ Play video
dry violet
maiden heath
#

can i reverse an animation in unity using animator?

dry violet
#

speed -1

maiden heath
dry violet
#

animation.speed

maiden heath
dry violet
#

No idea

maiden heath
#

ok well thanks anyways

#

i set animator.speed = -1 but it didnt work and i got a warning

dry violet
#

you have to change the specific animation you want to invert

gaunt holly
#

Thank you @daring cove @dry violet

lofty summit
#

I have a Spline object (from inside a SpriteShape), is there a way to get points inside the spline like "traveling" it? Not just the control points, but intermediate points inside the spline ๐Ÿค”
GetPosition only asks for an integer and returns the control point, I need something like... evaluate?

trim schooner
#

Do GetPosition and GetPositionTangentNormal replace parts of it?

lofty summit
#

Oh, I think that my problem is that Spline is not a UnityEngine.Splines.Spline but a UnityEngine.U2D.Spline ๐Ÿ˜

#

yep, different splines ๐Ÿคฆโ€โ™€๏ธ

#

yay, fun ๐Ÿฅฒ

#

Ok, I can make an in memory UnityEngine.Splines.Spline from the control points from UnityEngine.U2D.Spline

lapis acorn
#

does Unity has an option to auto initialize a prefab on game start?

In Godot for example there are "autoloads". Does Unity has something similar? I want whenever i start playing a scene, that specific gameobjects and scripts are added to it as DontDestroyOnLoad

mellow sigil
#

Just put them in the scene?

lapis acorn
#

I have several managers. When i want to test some things isolated, I do not want to add all these dependencies just to test a small thing. they should be automatically added whenever i need them

heady iris
#

The Safe property is used in places where I don't want to create an instance (like while the game is ending)

#

Otherwise it's straightforward enough: this loads a prefab from a Resources folder

#

My GameController class bootstraps itself like this:

#
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        private static void OnLoad()
        {
            Instance.Initialize();
        }
lapis acorn
#

interesting ๐Ÿ˜„

heady iris
#

It then loads other singleton prefabs, like the menu UI and the input controller

vale wharf
# lapis acorn does Unity has an option to auto initialize a prefab on game start? In Godot fo...

I think you're referring to a pattern called "bootstrapping", where you load required scripts/assets when the scene loads instead of having to manually place those assets in the editor every time you make a new scene.

For my game, I do this:

public static class App
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    public static void Bootstrap()
    {
        bool shouldBootstrap = GameObject.Find("NoBootstrap") == null; //Don't bootstrap scenes with a NoBootstrap GameObject
        Vector3 bootstrapPos = GameObject.Find("BootstrapPos")?.transform.position ?? default; //Allow for defining a specific pos for the bootstrap prefab to be spawned at
        GameObject target = GameObject.Find("Bootstrap"); //Check if bootstrap prefab is already loaded

        if (target == null && shouldBootstrap)
        {
            target = UnityEngine.Object.Instantiate(Resources.Load("Bootstrap")) as GameObject;
            target.transform.position = bootstrapPos;
            if (target == null)
                throw new ApplicationException("No app prefab found in resources!");
            //Don't destroy bootstrap prefab when a new scene loads
            UnityEngine.Object.DontDestroyOnLoad((UnityEngine.Object)target);
        }
    }
}
#

you can then implement the singleton pattern on specific scripts that are loaded in the bootstrap

#

though be warned, I think this will cause the prefab to be instantiated AFTER Awake() and OnEnable() is called on monobehaviours in the scene, but before Start() is called.

#

so for example, if one the objects in the bootstrap prefab is the main camera, anything trying to get the/find main camera from Awake or OnEnable will find nothing (null).

hallow valve
#

Do you guys know why it's giving me this errors when I build the project?

This is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using TMPro;

[CustomEditor(typeof(FieldOfView))]
public class FieldOfViewEditor : Editor
{
    void OnSceneGUI()
    {
        FieldOfView fov = (FieldOfView)target;
        Handles.color = Color.white;
        Handles.DrawWireArc(fov.transform.position, Vector3.up, Vector3.forward, 360, fov.viewRadius);
        Vector3 viewAngleA = fov.DirFromAngle(-fov.viewAngle / 2, false);
        Vector3 viewAngleB = fov.DirFromAngle(fov.viewAngle / 2, false);

        Handles.DrawLine(fov.transform.position, fov.transform.position + viewAngleA * fov.viewRadius);
        Handles.DrawLine(fov.transform.position, fov.transform.position + viewAngleB * fov.viewRadius);

        Handles.color = Color.red;
        foreach (Transform visibleTarget in fov.visibleTargets)
        {
            Handles.DrawLine(fov.transform.position, visibleTarget.position);
        }
    }
}
runic island
#

Hey I'm getting some weird errors that aren't making sense to me. Maybe someone with more experience can point out what I'm doing wrong? Been working on this since yesterday. I got majority of the issues worked out but I'm at a loss for these last three.

The code is from a 2023 tutorial so maybe some things in TextMeshPro changed since then but it's just not clicking for me, I've been working on it since yesterday to no avail. https://pastebin.com/J6P8Jb1Q

I put the error codes in the comments along the code.

knotty sun
naive swallow
runic island
# knotty sun just use TMP_Text which is applicable to both UI and World TMP Text objects

I see.. Since my game is 2D, do I even need to use TextMeshPro at all? If I understand the API it's used for text in a 3D space, and all my text is going to be on the canvas so I should be good to just use the TextMeshProUGUI.. I think? If that's the case then I can simply get rid of the second constructor and everything should still work. I believe I do want TextMeshProUGUI for the addition event handling and UI integration over TMP_Text.

If any of this is way off-base please correct me. I'm mostly trying to get an understanding of how the typewriter effect is done for text panels as well as click and pointer interactions which is why I'm not using an addon.

knotty sun
#

and yes, get rid of the overload

runic island
#

why do you need TextMeshProUGUI? TMP_

mental solar
#

Hi, I'm having issues with the new Input System.
I'm rewriting all legacy OnMouse...() buttons to use the new Pointer events, but some buttons work and some don't, how do I debug this?
I've added this code to a script which is attached to the Main Camera game object

heady iris
#

OnPointerDown is not part of the new input system

#

are you trying to use this for non-UI stuff?

#

explain what you're doing

mental solar
#

trying to port a game to consoles, mostly
the developer put multiple canvases and colliders in a scene, the buttons are a pair of Sprite + Text + Box Collider 2D + some script with OnMouseDown
and with OnMouseDown the "buttons" work fine, but with the new Input System UI Module and OnPointerDown some buttons work (mostly those that are at the top of the screen) and most of them don't

small pollen
#

Can somebody help? the thing is, i have a "mute" button that when clicked, plays a sleeping animation and mutes the audio source. but when i do click it, all the gameobjects play a sleeping animation and mute

#

even though i want to be able to individually mute them

naive swallow
#

Show code

small pollen
#

lemme grab it rq

#

its shitty i know

#

(i use Spine animation)

#

And also

#

when the timeline requests the gameobject to play an animation it plays that animation instead of the mute animation

heady iris
#

OnMouseDown isn't a UI thing either -- it works on physics colliders (which is why it was working previously)

mental solar
#

I guess the "best" solution here would be to read Mouse.current directly, then raycast manually and dispatch events to gameobjects with a custom system

#

but maybe there's a better solution which I just don't know - I really don't want to re-do these buttons because this isn't my game and isn't my code

naive swallow
#

Is there a "proper" way to modify package code without just copying the whole package into Assets from the package cache?

heady iris
#

Unity will recognize that it's an embedded package and get rid of the copy in Library/PackageCache

#

and it will still understand that you have the package in your project