#archived-code-general
1 messages ยท Page 344 of 1
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?
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
You can easily cast a double to a float.
Yeah I guess I'm worried about loss of precision
Like how are miliseconds a double
If you intend to use WaitForSeconds, then you can only use a float. A double is more precise than a float. You're not going to get worse precision than float when going from double to float.
ohh, i thought it was the other way around, makes sense
ty
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)
you are not Disposing your CancellationTokenSource instances which may be a problem. Also how are you invoking this method?
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)
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 ...
the scripts on disable go are disabled too.
yes i know
that's why i create a empty GO
I copy every properties but it didn't work well
I have no idea what you mean by this question to be honest
you are trying to do a collision between enabled go and disabled go and checking ontrigger.
disabled go never detects collisions.
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
that's why I use an empty GO. Empty GO is like a copy of the item but without mesh. So i can use it to ensure that there is no agent on my position ๐
my English is very limited. That's why it's hard to understand me. I'm really sorry !!!
then why make the item go disabled just make the script which is spawning disable when the agent is on the spawner platform simple.
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
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?
If you have a bunch of variables and you need to increment them all, there's not much more you can do
Check it at the same rate that your character moves. So, if you're moving with a rigidbody, check it in FixedUpdate (and do it before you try to jump, of course)
roger that
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.
C#/VB/F# compiler playground.
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.
can you not just reference the VideoPlayer component?
i tried but i cant as it is not a part of the scene
the quad is not in the scene
so it's on a prefab, then..?
yeah
Yes. I really did a lot research about this thing :d Good to share 
i will try that
Hi, what would be the best channel to post a question I have about Unity As Library for Android Studio?
i am not able to wrap my head around this
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
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?
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
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?
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!)
Graphic has [ExecuteAlways] on it.
this allows for things to update as you work on your UI in edit mode
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 ๐
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
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.
what?
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 ๐
They broke all Custom Drawers (reported as bug, acknowledged - I have it from Unity officially). They broke all custom inspectors (reported as bug - they eventually fixed it). They broke all callbacks on RectTransform (reported as bug, QA refuses to allow it to be fixed, someone at Unity doesn't want to fix that one)
Graphic has been [ExecuteAlways] since at least unity 2020, just looking at a random example
They broke everything and you were the only one who noticed it?
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
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)
I cannot find anything on the issue tracker.
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).
I also cannot find anyone complaining about this kind of thing, which I'm sure would have been a massive uproar
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.
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.)
(I moved all my editor-drawers code to UIT, and other than being careful waiting for 3rd party code to update, stopped caring)
Which is hte part that you think might not be a good fit for Unity? There are plenty of games and assets that broadly speaking do that.
There are runtime importers for different kinds of assets.
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.
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.
Is this security related? Kind of like CSP? Like if its just a stream of bytes why do I have to serve it over HTTP?
No; it's just a weird design, as far as I can tell
There are, of course, libraries you can use to decode MP3/OGG
Once you get an array of samples, you can create an AudioClip https://docs.unity3d.com/ScriptReference/AudioClip.Create.html
and then use SetData
Custom user scripting is another beast. I haven't touched that at all yet.
Something like Lua would be reasonable.
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).
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 ๐
You can use UnityWebRequest with local files
ooh, you're right.
mildly cursed
is it posible to remove an element from a list by name?
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
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)?
can t i use this : list.RemoveAt(Convert.ToInt32(GameObject.Find("...."); ?
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
it s perfect for me
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
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
it's worth noting the issue lies in thin colliders, such as floating targets
If it's a non-kinematic rigidbody, try changing its collision detection mode
notably, this needs a .name in there somewhere to have any hope of working...
I remember switching it to other collision detection methods but didn't have much luck
let me check something
Note that both the bullet and the target need non-default modes
i just thinked it is working
i don't know what this is supposed to mean
then no it definitely does not work
the target in question has no rigidbody, so what exactly would I need to change on them?
For best results, set this value to CollisionDetectionMode.ContinuousDynamic for fast moving objects, and for other objects which these need to collide with, set it to CollisionDetectionMode.Continuous
so you'll want to get a rigibody on the target
I believe it can still be kinematic.
wack. how about interpolation on the bullet?
Interpolation is purely visual
It has nothing to do with collision detection
noted
continuous dynamic mode on the bullets themselves changed nothing, so I'll go ahead and plug the kinematic rigidbodies on the targets
no dice
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
increasing the hitbox's size helps, so yeah
ah, ok
specifically behind it, making it wider
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!
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
show me the bullet inspector
also, how are you moving the bullets? are they non-kinematic rigidbodies that you just set a velocity on?
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
oh, this is using triggers, not collision messages
I am unsure if continuous collision detection works for those.
let me swap this out for regular non-trigger collisions
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
so hey things are working now
only problem:
guns aren't supposed to shove enemies into the Nth dimension lmao
should be an easy fix at least. thanks for the help
Giving bullets a super low mass would be the physically-correct way to solve that
are you constantly setting the velocity of the bullet?
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
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
yeah. velocitychange is ignoring its mass, so that should mitigate the issue
thanks again for the help
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
Almost compiles, you need to sync the generic type constraints of TArgs to what the Dictionary requires
where TArgs : notnull
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
You mentioned an "error", I copy-pasted it in an online compiler and it yelled about TArgs not matching the constraints
ah, no, this was an error with trying to do Dictionary<,>
Ah, you can only use these in typeof normally
yeah
Unbound generics
Maybe that comes into play if you're using nullable reference types
Nah it was a hard compiler error, though the compiler is on .NET 8 so it might not exist on Framework
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

Anyone got any idea why the IL2CPP build fails but mono passes? I get this error
'hash_compare': is not a member of 'stdext'
๐
I can only assume that you don't have the correct dependencies installed
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
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?
this isn't doing what you think it's doing. You're copying data on the GPU, but reading system memory. You probably want to be using https://docs.unity3d.com/ScriptReference/Rendering.AsyncGPUReadback.html or https://docs.unity3d.com/ScriptReference/Texture2D.ReadPixels.html
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.
Hmmm... Check the log files to see if there are any other messages.
Also, does it crash or freeze?
Unfortunatelly, did already check the logs. no further messages. it just freezes, no crash.
If so, you could try breaking with a debugger. Might need to attach it to a process, instead of using the default attach to unity mechanism.
i'll give it a shot. thanks
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.
There should be some info in the log files.
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.
Well, the stack trace is important. What does it say?
it pinpoints exactly to the SendWebRequest
I see. What unity version are you using? Did you search online for similar issues?
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)
Maybe it's some old package cache? Did you try deleting the library folder?
oh great idea! gimme a sec
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)
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
choose a block based on height?
Yes
It was a suggestion, not a question ๐
I dont know how i can do that because is a procedural world, the height always is changing by perlin noise
Presumably you're looping through the values of the perlin noise, so value = max height for that column. So top block gets grass, blocks below get dirt?
I'm thinking to divide the height of any colum and position objects using that
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
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?
if its an observer why does custombutton need to know about observer ?
wouldn't custom button just fire event for button observer to listen to ?
Yeah youโre right that would work here. Thanks!
Are there any limitations to the event approach? Because the observer pattern demands the ability to add and remove observers so wouldnโt it require that the observed object knew its observers? I suppose that can be done through subscribing and unsubscribing to the event
pretty much , only the observer needs to reference the button
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!");
}```
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
- Camera renders to RenderTarget.
- RenderTarget applied as material input.
- Render Model with the material.
Or is it possible for the sequence to go:
- Render Model with the material (but RenderTarget input has not been updated yet)
- Camera renders to RenderTarget.
Exactly, thank you
I'm thinking that i dont know xd
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?
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
I want to create a code to generate terrain with an unestablished list of blocks, my idea is that the blocks can be generated in an order no matter how many blocks you add to the list
The terrain is not generated with a fixed height, but it is generated with a maximum height that cannot exceed
i meant what specifically is the issue? like you say you dont wanna use an if statement which implies this entire thing could be solved if you use one.
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)
im confused really on what the issue is really. saying you would like to do a foreach doesnt clear things up because i dont know what blocks you even have, if you have a list of blocks with properties (like conditions of where they should be) then whats stopping you from actually placing these?
I seed you a dm
dont, read the server rules. keep it in here
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
The coordinates always make me nauseous because I have little imagination.
you'll need to show the code and what you're specifically stuck on, because if you have all these conditions already coded then i dont see what the issue is
or really just look into what minecraft does since this seems to be a clone
I can't generate the blocks in the order I require. If I want to generate random blocks depending on the height, how do I do it? I mean, how do I do something like this?
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?
:T i take a photo beacuse i send in WhatsApp :T
Then send it a different way ๐คทโโ๏ธ
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?
Enum is original class
just like string is String
enum is for example when you want to declare new enum type,
Enum contains static methods you can use
I'm reading this post about it as well https://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string-in-c
so similar to the string thing enum is the C# alias for the original Enum class? Something like that?
keyword for creation vs the actual implementation basically
Can I say that string and enum are both created for the purpose of easier "creation" of their original types
I see
its just an alias
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.
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```
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
have you tried AddComponent with a reference to the component u want to copy?
no? but i will now
thx
Hi, I downloaded for the first time and I can't open a new project
how do i set notification icon with unity mobile nofitication's unified API ? it is really driving me crazy
you might want to spend a little more time clicking around the documentation
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?
@spring basin This is a code channel
could you please redirect me to the channel where I can ask this question? Thank you
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.
Closest thing for long form questions/conversations here is #1157336089242112090 , create a thread there.
thank you
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?
move your fallposition calculation inside the while, presumably the transform.up is changing due to the rotation
transform.up will be changed if parent is rotating
and you use this in your "original" calculation
@vale wharf check your inbox!
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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)
if it was the gameObject it was complaining about why does the error message say object of type 'WordInteractable' ?
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
I don't know, the line 46 of WordInteractable.cs is the if (gameObject != null)
I know if you put your desired file in the Resources folder you can search it from there
Whats a resources folder
thanks
I recommend you to use addressables, its a better approach : https://docs.unity3d.com/Packages/com.unity.addressables@1.19/manual/index.html
interesting
thank you
Maybe it could be due to having the gameobject already destroyed but i dont know why the if would make an error
show code for WordInteractable.OnGameOver
Is that remove method called from an event somewhere?
its litterally calling Remove :
private void OnGameOver(object sender, EventArgs e) {
Remove();
}
here is the entire class https://pastecord.com/ekydyxytuf.cs
the method is private
Make sure you unsubscribe properly. And don't subscribe more than once.
OK, I think you are trying to Destroy the holder of the event which is being processed
i would agree, but it would have an error when subscribe or unsub more than once, i've already had errors linked to more than one sub and unsub, and it makes an error right away
i don't quite understand
What error does it make?๐คจ
it says that you can't subscribe twice to an event and can't unsubscribe to an even that you are not sub
Hmmm... Is that a unity event or something?
I don't think regular C# delegate events throw an error like that.
Csharp events : public void event EventHandler
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
Ah, it's an EventHandler
ohhhh maybe yes, i'll look that
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
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?
I try this way
because it throw an error and stop the game
no, I mean why bother destroying, a scene Load will clean up anyway
moving it at the beggining is the same
Its a VR game, the scene is the same, some buttons appears to restart the game or go back to the main menu, the Words disapear ( the words are entities of the game, its a game about writing words)
so they disapear when they are touched or the game is ended
It might work if you check for if (this != null) instead
i have a warning saying this is always != null
how can this be null and yet still be executing?
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
by events, i would agree that this could be "partially" null
Unity objects override the null check so destroyed object == null
the problem is he is trying to Destroy the object which is executing the current code
No, the problem is trying to execute the current code on a destroyed object
it worked ^^ thanks
events are strange
thet just means the Destroy never happens.
Use the debugger to check
The object is already destroyed
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.
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.
Vector3 originalPosiition = transform.position;
Vector3 fallPosition;
float elapsedTime = 0;
while (elapsedTime < fallDuration)
{
fallPosition = originalPosiition + (transform.up * (-fallDistance));
transform.position = Vector3.Lerp(originalPosiition, fallPosition, elapsedTime / fallDuration);
elapsedTime += Time.deltaTime;
yield return null;
}
like this?
Is there a way to return a yield instruction ?
ie. if(bool) return "yield return null"
else return noyield ?
what would be the point of returning noyield. Just don't return
I can't return nothing lol
so dont return at all
yield break; ends the coroutine immediately. maybe you want that? But you absolutely can just.. not return anything.
yield return null
Doesn't work. It skips a frame no matter if true or false
public static IEnumerator CheckFixedTimeStep()
{
if (Time.inFixedTimeStep)
{
yield return null;
}
}
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
public static IEnumerator CheckFixedTimeStep()
{
while (Time.inFixedTimeStep)
{
yield return null;
}
}
Doesn't work. Still skips a frame when Time.inFixedTimeStep is false.
print(Time.frameCount);
yield return CheckFixedTimeStep();
print(Time.frameCount);
=> 101 then 102 even when from Update
Bump
yes.
yield return StartCoroutine(CheckFixedTimeStep());
I presumed you knew how to start a coroutine
Doesn't work, exactly same issue as above
Maybe you want WaitForFixedUpdate..?
What is the point of this coroutine?
delaying the beginning of the coroutine for one frame if and ONLY if it was started from fixed update
so why the separate coroutine what is wrong with
print(Time.frameCount);
if (Time.inFixedTimeStep)
{
yield return null;
}
print(Time.frameCount);
Although I'm not convinced inFixedTimeStep applies to Coroutines
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
No this is not correct
Yielding another coroutine will always result in an extra frame
why does OnTriggerExit2D not show up in intellisense
Seems so. Is that a bug ? Yielding an empty coroutine still results in an extra frame
Not a bug, just a consequence of the coroutine system
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.
has anyone bothered with calculating the distance between two points in any number of dimensions?
It's the same math for any number of dimensions.
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);
}
}
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?
I can't explain lol
so you have a problem, but you can't articulate what the problem is...?
idk how to prove that my Distance function works either
well the problem is a long story ๐
You could at the very least make sure that it works with 2 and 3 dimensions by comparing to Vector2/3 distance or making some math on the paper.
If it works for these 2, it likely works for any dimension.
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
I will compare Unitys 3D distance with my 3d distance then
This is why the hypersphere has such a tiny volume. It takes up very little space in the hypercube it's embedded in.
it does work for the 1st, 2nd and 3rd dimensions at least
maybe my problem isn't with the distance calculation then
well, you'd better start telling it if you're still having problems!
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
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
lol
and I thought I came up with a really innovative way to make a neural network ๐
If you add dimensions but keep the number of points constant, your density falls off a cliff
and you're encountering this exact problem
The volume of a high-dimensional hypersphere with radius 1 is way smaller than the volume of a hypercube that's 2 units across
๐ค
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)
What about that setup involves "learning"?
it's just a mutation algorithm
I presume there's some process that minimizes the distance
whoops, wrong reply
(i hate how spheres are off by one)
and yes, that's the selection criteria for my mutation algorithm I guess
If you keep cranking up the dimensionality, then points randomly positioned inside of a hypercube get further and further apart.
but they are not cubes tho? They are spheres cuz they have a radius
I'm talking about randomly placing points
Isn't that what neural networks do already with back propagation?
I'm just experimenting different ways lol
that's one way to train a network, yeah
but there's no rule that says you can't just randomly wiggle around
or that dogs can't play basketball
Yeah. What I'm trying to say is that the simpler options were probably already explored by many researchers before.
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
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"
wdym by factorial in the denominator
I know what factorial is but I'm confused in this case
gamma extends the factorial function to non-integers
this function crashes to zero very quickly
High-dimensionality spheres have basically zero volume.
so I just increase the radius for higher dimensions
you have to increase it a lot
how do i get rid of the box icon? im using aseprite importer
That means that this object is a prefab produced by an importer.
If you unpack the prefab, it becomes a normal object
(which, of course, breaks the prefab connection)
how do i unpack it? right click?
Why do you want to do this?
https://en.wikipedia.org/wiki/Curse_of_dimensionality
see the "Distance function" section
isnt the box icon supposed to not be there
it explains the exact problem you're encountering
...no?
oh that was the impression i got.. i thought the box icon acted like a zip folder
In this sense when points are uniformly generated in a high-dimensional hypercube, almost all points are much farther than
runits away from the centre.
If you unpack the prefab, then changes to sprites will still work -- since the object is referencing those imported sprite assets. However, any changes to the prefab will not be reflected.
oh i see
this is more obvious with 3D models -- if you add another object in blender, the unpacked prefabs won't get the new object
the math doesn't give me much but I think I get the point you are trying to explain
I dunno if this actually matters for the prefab created by the Aseprite importer. If it just makes an object with a sprite renderer and an animator, then there's nothing really stored in the prefab itself
it just references an Animator Controller and some sprite assets
in that case, it doesn't matter if it's unpacked or not
but I also just noticed that my algorithm struggles to learn the more "neurons" it has so increasing the dimensions means increasing the neurons
"WeaponManagerController" is a mouthful
both "manager" and "controller" imply that they operate on many objects (especially "manager")
To maintain the same density of points, you have to double the number of points every time you add a dimension
"GunPickupAndThrow" 's job is to pick up and throw weapons. The name should indicate this.
I remember suggesting "WeaponHandler" for that reason
why am I not allowed to say "hmm"?
the server blocks a lot of no-content messages
lol
I do get whacked by the "hmm" filter from time to time
I noticed you were creating points with values like [1, -1, 1] in that code you briefly posted
Those points are positioned on the corners of the 3-cube
yes cuz I'm converting the values with Tanh
so they are in range -1 to 1
The distance from the n-cube's corners to the surface of the [n-1]-sphere gets larger and larger as you add dimensions
[n-1]-sphere meaning the edge of the sphere?
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 (:
You very quickly hit a point where a unit sphere on a corner and a unit sphere at the center don't overlap
Correct.
so that increases in higher dimensions
That distance grows as you add more dimensions.
yeah it makes sense when you compare the distance in 2d vs 3d
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
so should I do something like radius = Pow(radius, dimensions) ๐
sqrt(d * x^2) = 1
therefore, x trends to zero as d increases
I suspect you'll have trouble getting meaningful results if all of your points have a very large radius
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?
link doesn't work
but what if I normalize them so they have the same relationship but stay between -1 and 1
I'm guessing you forgot to call SerializedObject.ApplyModifiedProperties();, but that's a shot in the dark right now :p
I don't know what that would mean
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
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
Do you have root motion enabled on the animator?
If your animations contain root motion, they could be causing you to move around suddenly
Yeah the tutorial is for use with root motion nav agents
I updated the link.
Your code isn't using PropertyFields. It's just directly modifying the fields on a C# object.
I'm not sure what the correct move is here, actually
I'd ask this in #โ๏ธโeditor-extensions
okay, thanks
The desired velocity is proportional to the distance to the agent's next position. That sounds wrong...
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
I'm pretty fresh to it, so not really too sure what to actually do in these examples at the moment ๐
So in regards to the InverseTransform you mentioned, and normalizing. How would I make these changes?
I assumed the normalize you mentioned was for the shouldMove bool, but I'm not too sure atm
Still trying to come to grasps with it
@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
Vector3 worldSpaceVector = /* something */
Vector3 localSpaceVector = transform.InverseTransformVector(worldSpaceVector);
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.
So, I understand the idea you are mentioning there, but I'm just confused as to where exactly I add/edit this in to the script I pasted?
Still wrapping my head around the tutorial so not sure what's what yet in this logic ๐
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);
i can use scriptable objects to make a dialogue system right? because im not sure how they work
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
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
oh yeah, I've seen this logic before (and used it)
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
Makes sense so far yeah
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
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
you'd start from your current position
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);
}
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
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?
yeah, that was the problem
thanks
it didn't occur to me that it would be in pixels instead of units
well, those are roughly equivalent here
I was using the same constant I had used for other gameobjects so thats why it barely moved
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
What is the best way to optimize the performance of a game? (cullings)
I tried with chunks, but I couldn't do anything
It varies completely game to game.
Step one is always to profile though
The game could be considered an open world, it has procedural generation, and I have the idea of โโmaking the map relatively large
Chunking is relevant to that.
Step one is still to profile
What do you mean with profile?
The profiler
You should look up a guide on how to use it. The hierarchy view is going to be the most helpful
Okay, ty
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
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
Waow, I studied the full demonstration of this formula last year, didn't think it would ever be useful ๐ฎ
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?
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
The way I like to think about ScriptableObject is that it's how you create your own asset types, just like how MonoBehaviour is how you create your own component types. More descriptive names for them would be something like CustomAsset and CustomComponent.
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.
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?
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.
I don't understand what you mean by this.
to store hold audio's temporarily for my audio handler
My apologies. It was meant to be store / hold.
Yeah, "CustomAsset" is a much better description
Explain what this actually means.
What will you be doing with this object/singleton?
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)
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
how ? why does BuildingSO know about Building
You don't want the class on the actual prefab
It should be on an empty just for placing, then you instantiate the specific building prefab when placed
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
Upon instantiation make it a child, sure.
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
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
isnt the prefab just a visual? whats it got to do with building class
But i need the prefab to instantiate a building
Im talking about the one on the SO
don't you have something like this
public class BuildingSO : ScriptableObject
{
public string buildingName;
public Transform visualPrefab;
public int cost;
}```
When initiating the building itself, i get the game object from the SO
so the example I wrote basically?
yeah just a GameObject instead of Transform
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
yeah i think i'm a little dumb tonight sorry
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?
Video of non rotating planet: (player rotating works!)
Video of rotating planet: (player rotating doesn't work)
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);
}
}
does the player fall over when trying to rotate left or right?
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
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
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));
}
}
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
this is how it should work increasing the y rotation every frame (this is with planet rotation off)
this is with it on, it's weird how it jumps about
sorry for writing over you
you can draw the sphere cast using gizmos, maybe that should help you
Are you having problems? It looks fine to me, assuming that transform.position = target.position; is there for a reason.
Yeah the transform is meant to follow a target since this is just a test
I did try something similar and it generally looked fine which is why I'm confused
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 ๐ค
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)
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
I'm not though
maxDistance param
Wait
Consider using CheckSphere() if you don't need info on what you hit (just whether you hit or not), or OverlapSphere() if you do
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
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
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
Your line is 1 unit long, it doesn't correspond to the spherecast. It only shows the direction, not length
But sphereScale is also only 1
So is it intentional that you spherecast with the sphere's radius as the max distance?
Yeah
Doesn't the spherecast ignore any colliders it starts out inside of?
Yes
Also, you're using a new enough version of the editor to turn visualize queries with the physics debugger
That may be illustrative.
Ooh I haven't heard about that
If the radius is 1 then it definitely starts inside that box
Sorry should clarify that I moved it. It starts on the other side of that box 5 units away
Okay, and your max distance is 1 so it wouldn't hit it
Yeah that's why I moved it
Okay so this helped a TON
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
presumably you mixed up your diameter and your radius
Yep rip lol
yeah, unity spheres and cubes have diameters of 1
(well, cubes have edge lengths, not diameters, but same idea)
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
"managers" are perfectly fine
you're obviously going to have something that's in charge of how buildings are getting placed
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
You can still maintain encapsulation. The manager doesn't need to be able to access the internal state of the buildings in order to place them. Encapsulation doesn't prevent cross-object interaction, it facilitates it.
Exactly.
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
You'd tell the building that it got placed down.
you're asking "how do I write methods?" at this point :p
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
You might want to read the C# Learn docs about object-oriented programming
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/inheritance
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
Maybe my problems are more fundamental tho I'll take a look thanks
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
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:
you've attached the "Camera Controller" script to the player object
that doesn't seem right
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);
}
}
exactly, i had it solved before, but i honestly forgot if i had a emptyObject for the camera controller (player's child)
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);
}
}
your script is rotating the actual character object here
so of course when you move forward it will go in the air
when you're facing in the air
how am i solving it?
Your code looks like it's intended for a first person game
do i create a child "Player Camera" for "Player" with the camcontroller??
it swapps between both cameras
you're using the FPS script in TPS mode
don't do that
ohh
i see
i meant gameObject*
now the camera doesn't follow the mouse
but isn't there a script where i can get both fps and tds working?
You can write one
i'm working on that, since i need to do a little research about the sync
Someone could help me with a terrain generation?
Ask your question
I want to do something like this
But when i try this happens
Like layers
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
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) ?
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
IS a block class, contain values like the Sprite, the Minimum level yo spawn, the height level and things like that
Some bool values
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
Yes
And I Would use that instead of thickness?
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
That would me work with mรบltiple blocks? Like adding grass Stone Clay infinite blocks?
That's the point, you add different depth values to different BlockDatas
I dont have a fixed listo of blocks
And how put in? Like i am doing in the method createblock?
Replacing the current if(y < localY) is the idea
This is the simplest way I can think of - there are improved alternatives
How?
question to the hive mind. Has anyone created a movement/collision detection system without physics (with the intention of better performance) ?
I guess how do you define physics? Changes in position and collisions are physics. Do you mean not using the physics ENGINE?
I think collision detection is inherently "physics"
but uh - sure I've done lots of grid based games and stuff that didn't involve the physics engine
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...
you could always use coroutines in the editor
also #โ๏ธโeditor-extensions for editor related coding
i guess, it feels clunky that I have to install a package to wait for something asynchronously in their base API.
wdym by "list request"?
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?
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
oh and all my lights are set to Mixed mode and I'm baking with Subtractive mode
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
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
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 !
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
Haha could just use a simple raycast to check if 1 point is obstructed
recently i was thinking about how to calculate wallbang
Or use the Out parameter to get info on that what's been hit
in competitive tac shooters bullets can penetrate walls
im thinking about how to calculate that
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
why not use a boxcastall from the player to the enemy. if the size of the box is the same as the enemy then it should pick any part of it exposed
Doesn't box cast get blocked by the closest hit object instead?
I said BoxcastALL
xD But box cast all means all targets in the boxcast's path
yes, which is what you want is it not?
I mean, I suspect that it does not account for obstruction
then it is a simple bounds check to see what is obsuring what
Instead gives all the box cast results as if the rest doesn't exist
What is a bounds check in this context?
colliders have a bounds property. I suggest you go and read the Bounds docs
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
is there a way to code my own node based dialogue system graph thingy?
yes its possible, lots of work but many companies have it already
theres a few tutorials on it actually
In this tutorial series we'll be making a node based dialogue system using the Unity Experimental GraphView API.
It will have a series of features that you can check out on this video or in the dialogue system features video.
Timestamps:
00:00 Introduction
00:50 Features
01:10 Referenc...
first video i found on it
oooh thank you!
this seems really cool
easier than having a shit ton of if statements for my dialogue
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
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?
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
It seems to me that it is because of the vsync that the headset has, reducing the render load will possibly improve it
You can have a look at the render thread
is graphview api deprecated?
Use the hierarchy mode, as it's easier to see what takes time.
the one that is completly empty ? because their is not one else
Yes, that's why you should use the hierarchy mode.
i dont have vsync enabled
this is the hierarchy mode of the render thread
Seems like it's mainly waiting for the GPU to finish it's work.
You could try looking at the GPU module if it works on your hardware
i dont know how its work
If you do the build in the glasses, does it also happen? it could be because of the connection
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.
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
If i build i also have low FPS
Sorry, I saw your answer late. I donโt know, I suppose to create basic terrain and after build roads on it but with unity system or add 3d model I created. What is the best to have the best similitude with GTA ?
3d model
i can't use GPU profiling with Vulkan
Okay, so I must create portion of road in 3d and add it on my terrain ?
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
yes like a kit, There are addons in blender to make roads
Then look up platform specific profiling tools
Other than that, you just need to optimize the GPU processing time.
i'm doing some research, i'm not sure where i can find some, i'll look
yep that's the issue
Try looking for vulkan specific tools.
yep thanks
Found this. Its a unity forum article.
https://forum.unity.com/threads/best-approach-to-creating-dynamic-roads-that-follow-a-path-of-data-provided-shaders.860272/
hey all, Im here with another shader question, however, it's more of just a question about the right approach to use.
I have a procedural generated...
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
...
can i reverse an animation in unity using animator?
speed -1
animator.speed?
animation.speed
is there a way to do it from the animator
No idea
oh
ok well thanks anyways
i set animator.speed = -1 but it didnt work and i got a warning
you have to change the specific animation you want to invert
okay
Thank you @daring cove @dry violet
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?
spline 2.5 had evaluate but 2.6 doesnt? ๐
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.Evaluate.html
Do GetPosition and GetPositionTangentNormal replace parts of it?
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
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
Just put them in the scene?
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
I handle this with a SingletonPrefab class.
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();
}
interesting ๐
It then loads other singleton prefabs, like the menu UI and the input controller
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).
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);
}
}
}
on vscode I have no errors
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.
Here's the entire class so far if it makes a difference. https://pastebin.com/g8zxPuVW
just use TMP_Text which is applicable to both UI and World TMP Text objects
You cannot include anything in the UnityEditor namespace in a build. It needs to be excluded either by putting it in an Editor folder or using Assembly definitions
ok ok, thx
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.
why do you need TextMeshProUGUI? TMP_Text is the standard way of using TMP Text variables
and yes, get rid of the overload
why do you need TextMeshProUGUI? TMP_
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
OnPointerDown is not part of the new input system
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/EventSystem.html
That's part of the Unity UI package.
are you trying to use this for non-UI stuff?
explain what you're doing
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
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
Show code
lemme grab it rq
not sure which to give so im jus givin em all
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
None of those are UI components. They do not make sense on a canvas.
OnMouseDown isn't a UI thing either -- it works on physics colliders (which is why it was working previously)
here's how a typical button in this game looks like:
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
Is there a "proper" way to modify package code without just copying the whole package into Assets from the package cache?
Copy it into Packages/
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