#archived-code-general
1 messages Β· Page 292 of 1
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/kifuwotova.cpp and https://gdl.space/yezurixapi.cs two main scripts
How do I merge a main with a building inside it so I can enter the building (both have collider along with the player controller) + remove the larger mesh parts where both meets ?
Is this something that is done with colliders/mesh filters settings or it has to be done by code ?
Tried to find unity learning mesh merging unity learning mesh overlap but couldnt find anything π¦
Is this something you have to do at runtime? If not I would just do this in like blender, there is also the probuilder tool which has some functionality like this but it's kinda shit
what do you mean by "a main with a building"?
main entrance?
So it seems like rect transform is a problem, like it doesnt recognize it is on the object
Im sure the problem is in unity as it works well on autors project
no, the problem is in your project.
If CardContainer isn't attached to an object with a RectTransform on it, then rectTransform will be null
i know, i just meant it is in unity side not code
I have a free terrain that is a glTF I dont have access to the original mesh. It's not a unity terrain just a mesh with a collider I use to walk on. I want to put an underground cave throught one of the mountain on it but I cant enter it because the mountain block me and the mountain render over the entrance
everything else work except I cant enter the cave
cuz my controller collider collide with the terrain collider over it
well, it is
you probably could find a tool that removes the triangles that intersect some volume, its not exactly boolean operation, but simply remove tris at runtime
i send this script as well
unity terrain supports making holes in a similar fashion afaik
I'm looking for the inspector for the object with CardWrapper on it
Im not sure how to convert the mesh to terrain either, I mean the mesh came with its own terrain textures I dont want unity to use its own terrain texture...
Card wrapper is a script that attached to the objects that are childern of container during playtime
yeah so im suggesting either writing a tool that removes tris yourself, or find it, or edit the mesh in any 3d package
until then I guess Ill just use a trigger zone with playmaker to teleport me until I find a solution
Yes. I'm asking you to check that those objects have a rect transform on them
You could log a warning in the Awake method of CardWrapper to see if any instances are unable to find a rect transform.
i did before asking
That object does not have a CardWrapper on it.
Does clicking the first error highlight an object in the hierarchy?
You'll need to do that while the game is running
yes, it does with container, but i checked it already
Awake doesn't run until the GO is active for the first time, so it looks like all but one of your CardWrappers is going to nullref. Does your tutorial also have all these objects inactive?
Oh!
Yes, I completely blanked on that
Awake runs once the object is activated
(the component can still be disabled)
actually it has them active
log something in the Awake method to make sure it's actually running
you can also log the resulting value of rectTransform
when in doubt, sanity check it with a log
The problem was that i didnt actually know what to log
like i forgot the difference between start and awake
Does the renderer for a child object not get disabled if the renderer for the parent object is?
no theres is no connection
Ok thank you
Is there a way to make it so i dont have to manually add each Element as its not just going to be one canvas layout but multiple for multiple games so itll be quite difficult to keep it managed like this
Well for one is the UI going to be the same in all of them?
If so you can just do this once. Make a prefab and reuse it.
You can also use prefab variants
as for things like PlayerX_Op - you can use an array, or just reference their parent object and iterate over them in code as needed.
no they'll all be differant differant games have differant data Like Rocket league doesnt need a KD and Operators ect
I'm evaluating a spline's up-vector about 120 times per frame. It's incredibly slow -- I turned on Deep Profile, so this is exaggerated, but it's still doing an enormous amount of work.
Asking for the position and tangent is significantly less expensive. I have no idea why calculating the up vector is so particularly bad here.
I guess this is some kind of iterative process, but still, holy cow
I'm using the spline to position and rotate about ten transforms, and I had 12 instances of that thing in the scene here
is that inside a job?
No, it's run straight from managed code.
back then i did tests and math lib was slower outside jobs than MathF
(quite a while ago)
I just switched to using splineContainer.Evaluate instead of working on the spline directly, and instead of calling the three Evaluate* methods separately
if (splineContainer.Evaluate(splineTime, out var pos, out var tan, out var up))
{
item.position = pos;
item.rotation = Quaternion.LookRotation(tan, up) * offset;
}
roughly the same behavior
I didn't realize until now that you could burst this, so I'll give that a try
i'm just startled by how quickly this ground to a halt
did you enable release mode?
release mode for what?
for the editor to see if any optimizations kick in
oh, rather than being in debug mode
it's in release mode
also, hm you can't just throw an entire Spline into a bursted method
ah, you have to allocate a NativeSpline
Anyone know if methods that use a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)] attribute run on the main thread? Or would there be a way to somehow to test that?
I sure hope it does
my game controller wakes up with a RuntimeInitializeOnLoad method
Looks like it's rebuilding the whole curve, as if you've dirtied it somehow
That is something I should have mentioned: I am deforming the curve every frame.
I'm guessing it'll be a lot happier if I don't do that
doesnt unity pretty much have everything on main thread?
There might be a form of evaluation that doesn't rebuild the cache
Because the cache is useless if you're constantly rebuilding it
ah, it pre-calculates a bunch of vectors, then?
yeah my understanding is that unity-provided methods run on main thread
I wrote a script that "parents" each bezier knot to a Transform
so that the curve follows the transforms around
You can also test it by storing current thread and compare with object.RefEquals
oh good idea, thx
I'm working on a package that has some shaders. The shaders are not referenced by any materials since material instances are created at runtime by my code. This causes the shaders to be stripped from builds.
This package will be used in multiple projects and I don't to manually add the shaders to the Always Included Shaders list in the Project Settings. Is there a way to automatically ensure the shaders are included in builds?
I could generate a scriptable object that references the shaders and then reference the scriptable object from a something included in builds, or write a script that adds the shaders to include list automatically, but that all seems silly to have to do.
I also saw there was a [ShaderIncludePath] attribute, but it's obsolete :/
Is there a good way to automate including shaders in builds?
ah, yeah, so whenever the cache is invalidated, it has to rebuild an array of up vectors
30 of them per knot
It looks like ISpline has a separate CalculateUpVector method that says it's "slow, but more precise"
and it looks like it doesn't interpolate between a pre-calculated array in the implementation
if you're creating materials at runtime, why not store a reference to the shader anyway? i assume you're looking them up by name at the moment
Yea. In this case the shaders are used by a custom render feature. I just wanted to avoid users of the render feature having to assign the shaders by hand when the feature is first added and the references are null.
One solution I just thought of was to put the shaders in a Resources folder since resources are always included.
Yes, this is a lot better. I'm also going to turn off the "spline aligners" when they are not needed (they're only used very infrequently, and I've had them running constantly)
gonna have to mess with Cinemachine a little to make its spline cart use the slower (and thus, faster) method
How about a custom editor for the renderer feature that automatically assigns the shader reference?
Otherwise, I'm not against the idea of using Resources for something like this. At least, if you can be confident that if your asset is present, it's likely being used and the shaders included are not too big or variant heavy.
yeah, I lean towards Resources when it's something that'd be completely pointless to do by hand
You can also create a IPreprocessShaders build processor to conditionally strip the shaders, if you have some way to detect whether they are actually needed.
every kind of "module" in my game (a MonoBehaviour that is attached to a specific entity (no, not the DOTS kind)) has an associated ModuleInfo scriptable object
it contains a name and description
the module just yanks the object out of Resources whenever it's needed (the name matches the module's class name)
this way, i can actually serialize the LocalizedStrings correctly
I wish Unity had a way to serialize static references to assets in the inspector.
Can you access the methods within a script if that script is disabled?
yes
Being disabled or even destroyed has no bearing on your MonoBehaviour class's code.
A disabled MonoBehaviour instance simply doesn't have a few messages sent to it (like Update and FixedUpdate)
A destroyed MonoBehaviour's code still works just fine. You just can't ask Unity for anything (like the transform of the object you're attached to)
I built an interaction system that includes buttons that the player can press in order to open doors, make platforms move, etc.
So far I managed to implement simple buttons. You press them and they do their thing.
Now I'm trying to make buttons that you can only press once. If you try to press them again after that, they won't do anything.
I see. In that case, is there any way I can make a button work only once without using a flag inside the script that's attached to it?
A bool field is exactly how I'd implement that.
I guess the button component could destroy itself, but that sounds a lot more annoying to work with
I see where you're coming from but to me, it seems like I'm making the computer perform needless work by using a flag. It's as if I'm making it check for a condition that I'm aware will never again be satisfied.
This is an extremely tiny micro-optimization to be worried about
don't even think about it.
just write code that's easy to understand and easy to extend
I tried using the Destroy method right now and it works fine. :)))
Thank you for taking the time to help me out.
sure, and what happens if you decide to put a tooltip that hovers over the button to tell you that it's disabled? now the tooltip breaks, because the button component is completely gone
I would destroy the component if the thing the component represents was completely gone
it's not gone; it's merely no longer usable
To be honest, I never thought of that. I was planning to only show a tooltip if the object could be interacted with.
But I think it's better to listen to your advice.
I'll just use an if statement.
Better than to give myself extra headaches in the future.
Does EnableKeywprd only work at runtime and not within editor scripts ?
how can I invoke a method that has parameters?
If you need to pass parameters to your method, consider using Coroutine instead. Coroutines also provide better performance.
alr thx
is it not possible to call a function of a scriptable object from an inputActions callback?
It tells me that I'm not setting the reference to an instance of an object so I imagine it had something to do with the SO
nvm I figured it out
turns out I was setting up the return value of a void function to a callback, when in reality I needed to hook up the function itself to the callback subscribe
do I get a role here when Ive gone throught unity learning so you dont give me the bot command to check out unity learning ?
love it when a github unity example has a file called ActuallyTrying.cs like they were going to say on discord : "Im actually trying and dont understand here is the filename and class to prove it"
you get a gold star in my book
trying to make my own slider but I'm still confused on clamping.
I have it follow mouse fine. How to keep the blue between the two orange lines ?
public void OnDragging(Vector3 mousePos)
{
var pos = transform.position;
pos.x = mousePos.x;
transform.position = pos;
}```
is this on canvas layer?
just a collider for now
assuming that your slider is vertical and not rotated, you can transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, min, max), transform.position.z)
I tried cs private void Awake() { initPos = transform.position; } public void OnDragging(Vector3 mousePos) { var pos2 = transform.position; pos2.x = Mathf.Clamp(mousePos.x, initPos.x + 0.2f, initPos.x - 0.2f); transform.position = pos2; }
Did not work
if its in world space you need to screentowroldspace it first
where is ondragging being called?
I'm past that, It follows mouse world position Correct. it just goes out of the orange lines
oh
wait nvm
when it goes out of the orange lines does it stay outside until you release the mouse?
It keeps following mouse on its x axis
but does it snap back into place after you release the mouse?
snap back? I'm not sure what you mean
I need blue not go past orange
https://streamable.com/eklv2r
so if that is vertical why is the code all about the x axis
just the way my camera is rotated right now
ok, and this is on what like a overlay canvas?
since there is no transformation of the mouse coords (screenspace) to world coords
just regular object with collider
also add some logging, see what values you are getting for transform.positon as you apply it
Is this code correct to clamp ?
#archived-code-general message
well you would want value, min then max as args but yeah should work
but like i said Debug.log
see if your expected range is just wrong or and what the actual numbers are
here is what's happening with this code
var pos = transform.position;
pos.x = Mathf.Clamp(mousePos.x, initPos.x + .5f, initPos.x - .5f);
transform.position = pos;
Debug.Log(transform.position);```
So, here's a question. Say I want to linecast to check if a certain target is in line of sight, but I want to filter out other similar targets that may be obstructing the line, but if I do that then technically I'd be filtering out the main target's layer too.
Is the idea to swap the main target's layer/tag just for that line cast then swap it back? Haha
Perhaps a dedicated layer "LineOfSight" that I flip on every target I check against, or will I run into issues with this idea? (I'd assume swapping layer is instantaneous and there shouldn't be any lingering problems if it's all executed together)
After the linecast, maybe you can check for other things like script? (Unless itβs just a regular object with no special components)
Quick question, if I have a class which contains a number of unity properties and a multidimensional array of objects and I wanted to convert it to a JSON file for saving and loading, what would be the best way to go about it?
Json.Serialize(obj); super easy one liner, newtonsoft.json from unity enterprises it is a static method
you can add settings to the call/use JsonSerialize<> constructor after that if it doesn't do exactly what you want
Can newtonsoft support serializing things like Vector3 and Quaternion?
keep in mind unity limitation that it doesnt serialize private members/properties etc by default
try ? it takes like 5 seconds
I see no reason why it wouldnt besides the unity limitations I mentionned, serializer serialize every members by default
why use random newtonsoft packages rather than the official one in the package manager window though ?
because versions before 3.0 did not support those types out of the box
which is clearly mentioned in the readme there
this is also not a replacement for the newtonsoft package, this is for use in addition to it
also unity's implementation is based on this one
It's very much not a random package π
Thanks a lot for that, worked exactly as I needed it to
just note that if you are using unity's fork then you shouldn't need that
void RicochetAbility()
{
Vector3 normal = (currentHitTarget.ClosestPoint(transform.position) - transform.position).normalized;
Vector3 reflectionDirection = Vector3.Reflect(transform.forward, normal);
hitRotation = Quaternion.LookRotation(reflectionDirection, Vector3.up);
}
This kinda works, but I'm having issues that if projectile hits a wall dead-on, it'll continue going straight through it. Any ideas?
nudging positions a bit does seem to help, but the reflection direction has become unpredictable a bit.
blah guess ill just use OnCollision, or maybe just raycast it
void RicochetAbility()
{
Vector3 collisionPoint = currentHitTarget.ClosestPoint(transform.position);
Vector3 normal = (transform.position - collisionPoint).normalized;
if(normal == Vector3.zero)
{
hitRotation = Quaternion.LookRotation(-transform.forward, Vector3.up);
}
else
{
Vector3 reflectionDirection = Vector3.Reflect(transform.forward, normal);
hitRotation = Quaternion.LookRotation(reflectionDirection, Vector3.up);
}
}
Actually that seems to be an ok bandaid for now
the normal zeroes out sometimes cause I guess the contact and position or too close, but the problem with nudging positions is like in what direction do I nudge if say the sides of the collider made contact first
so if anyone has any ideas for that
how are you getting the currentHitTarget currently? with raycast maybe just use the normal given from there. One case u might be getting weird functionality is because when they collide, the 2 objects might be overlapping slightly, and the transform position is being taken inside the collider
I'm getting it from OnTriggerEnter, but yeah it's probably cause it's all overlapping
oh yea OnTriggerEnter would be worse for that since it wouldnt stop objects from moving
even with raycast im not sure that would help. I would think a second collider maybe
raycast should be fine because it has the normal https://docs.unity3d.com/ScriptReference/RaycastHit-normal.html
its the normal of the surface hit
thing is, im not too sure where I would target with the raycast if not the collisional point
oh, you mean instead of using the collider entirely
I kinda just actually swapped over to colliders. Was using overlap for a bit but I've gotten to the point where kinematic controller will work with what I got.
Im working on generating a dungeon, and the algorithm places rooms as it goes, however, i need to check for room collisions when placing them. Preferably, i would like to do this before i Instantiate the room. Is there any way to get some bounding box information of a GameObject?
https://docs.unity3d.com/ScriptReference/Bounds.html
this is the most straightforward way if an AABB works for you. you can get it from the mesh renderer or the collider iirc.
oh, interesting, ill see what i can do with it, thanks!
this is a text wavey effect for text mesh pro. does anyone know any other cool ones _verts[_charInfo.vertexIndex + j] = _original + new Vector3(0, Mathf.Sin(Time.time * 4f + _original.x * 0.01f) * 10f, 0);
is there an equivalent to Task.FromResult<T> for Awaitable<T>?
i think you have to make a completion source and set the result, which isn't quite as bad as it sounds (awaitables are pooled so it's probably still only one allocation?)
cool, that did it. thanks!
i can see myself writing a helper method to do that whenever i get around to upgrading to awaitables π i wonder why they didn't include an easier way
i guess if you're frequently returning values with Task.FromResult it's worth considering using ValueTask instead of Awaitable anyway
I'm having an issue with the circle where it bounces back and forth rapidly.
this is the corrosponding code. using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball_Movement : MonoBehaviour
{
private Rigidbody2D rb;
float t = 0.0f;
public float x = 0.0f;
public float y = 0.0f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D Paddle)
{
rb.gravityScale = 0;
y = 3.0f;
Vector2 vel = new Vector2 (x, y);
rb.velocity = vel;
}
void OnCollisionExit2D(Collision2D Top_Border)
{
y = -3.0f;
Vector2 vel = new Vector2 (x, y);
rb.velocity = vel;
}
}
is it possible to make an optional out?
mfw when no ```
ref
THE USECASE IS FOUND
great
Or do you mean with a default value?
Ref would just not require the function to write it, if that's what you mean
thats what I mean
what do you mean?
Guys I want some information whenever I download unity install editor it's get failed I have rtx 4060 laptop why is this happening
If you want to be able to omit the parameter you'd have to just write another overload of the function
Don't crosspost
yeah I may be overcomplicating things
I was trying to rewrite my FindClosest method, which returns a vector3, to also optionally be able to return the object its attached to
when I should just write a FindClosestObject method
patience, young one
you also asked basically the most vague question known to man
"I download editor it no work plz explain"
I install 2021 unity editor it's getting failed
Move this conversation to #π»βunity-talk where it belongs and where you've already asked @sleek cliff. You don't need to tak eup three channels.
Nor is it a programming question.
alright
Ok brother osteel
Is there any reason I shouldn't use a static class with static functions for pure functions that are just library functions?
no, that's a good usage
ok thanks
I ended up creating my own FromResult method for Awaitable. My case is a little odd, cuz I'm using it for an dummy method. So, the real method actually does awaitable things, and my dummy one is returning a constant, hence the FromResult.
in case anyone wants to do that public static Awaitable<T> FromResult<T>(T value) { var completionSource = new AwaitableCompletionSource<T>(); completionSource.SetResult(value); return completionSource.Awaitable; }
private float _hitTime;
[ContextMenu("Hit Animation")]
private void OnHit() => _hitTime = Time.time;
ContextMenu doest not change the _hitTime value. This attribute only for Debug purposes?
When and where are you running the context menu thing?
Note that _hitTime is NOT serialized.
In play mode
All I want is just set the value by calling Hit Animation ContextMenu function
And why it has to be serialized?
is it possible for me to quickly add code to all instances of an abstract function (vscode)
Hmm, i dont think this is going to work, im not sure. My rooms aren't just squares
Duplicated.
I want to create the AnimationPlayer MonoBehaviour class for animation purposes. I want to run methods of the class asynchronously. What concepts should I use: Async/Await, Tasking, Threading, Coroutines?
Target platform is mobile
Coroutines or Async/Await.
I want to instantiate a gameobject after a gameobject ie. I want it to be a sibling. How do i do it?
Instantiate(thePrefab, siblingObject.transform.parent);
(make it a child of the same parent)
forgot to add. Lets say there are 4 child in the parent right. I want it to be the second one (index 1) when instantiated
Do you guys know what can be caausing this :
Objects are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!
When i create a new project and create a shadergraph, after a few minutes i start gettting this eerror. And once its there you keep getting it more and more until editor restart
I tried on the 2023 something version and again on the 6.0 one
@long hare Don't crosspost please. #π»βcode-beginner
alright
hey everyone, so im trying to make an ArmA-style zoom, where you can press right mouse to toggle aim down sights, but if you hold the button down for half a second it zooms the camera in
does anyone know how to set this up using the new input manager?
You can use an Interaction to create an action that's only performed once the button has been held for long enough.
yeah, but the problem with that is that the normal aim down sights also gets toggled when i hold down the button
i want aim down sights to not go if i hold the button down
Add a "Tap" interaction to the aim-down-sights action .
Tap requires you to press and release the button quickly
that works perfectly, thank you!
I closed my visual studio and opened it again
and viasfora was still not installed
does anyone know how to fix this?
It's possible that something is stuck in the background. I'd restart my computer and try again.
How can i tell if a collider is currently in collision with another collider?
I have a class that generates rooms of a dungeon. The idea is that every time i Instantiate a room, i run a check if it collides with any other room and if yes, it gets destroyed and replaced.
I thought i could just use the "OnTriggerEnter" but the problem is that my script is just on some empty object that has nothing to do with anything. Do i have to create a new script, place it on the rooms, and then read collision data from this script?
You can get a list of all the current collisions with a field on the component
Though I can't find what it is called
yeah i can't find anything like this in the documentation
Could have sworn I used it before
GetContacts() by any chance?
This accepts an array and it will fill the array with all the touching colliders
But I can only find this for 2d colission
Nvm, this one is for 3d I believe https://docs.unity3d.com/ScriptReference/Collision.GetContacts.html
I've got a general question about Singletons and "Managers".
Let's say I have several 'manager' type scripts in my scene. Each one of them exists in a single instance, so it makes sense to make them a singleton. The thing is, they have methods and events I want to invoke from different places throughout the game, so for example I may have 64 objects that refer to something from that manager several times per a game session.
It makes sense to cache the reference to a manager, but, obviously, I can't make a [serializedfield] on 64+ objects and drag the manager there. Not caching and calling Manager.Instance to get the singleton every time would not be ideal as well, cause I know that's much less efficient than caching it somewhere. I can't cache reference to this singleton during object's Start() or Awake() because, obviously, singleton may get initialized AFTER the object that tries to cache it.
I've read about Lazy Initialization of singletons and also I've read about using callbacks to cache this singleton into the object only AFTER the singleton is initialized, but I'm not sure that will work either.
Basically, I'm asking what is the standard, non-stupid way to handle Singleton caching, initialization, subscription, etcetera( when calling Manager.Instance over and over during runtime isn't viable)?
well this needs some contact point array, how can i get that from a bunch of colliders?
No, what it does is fill the array for you
The idea is that you give a large enough array for everything to fit in, because this saves on allocation
The reason is that this method is likely called very often so this increases performance
ohhh, so it goes over all the stuff in the scene and whatever is colliding, it returns?
You can also give it an empty List rather than an array. Unity will resize it for you then in case you don't know the size it should have
Yes, the collection (array, list) will then be filled
i just imported some custom packages/assets, does anyone know how this goes away?
They did this because it would otherwise constantly return a new array, which is where the extra allocation comes in
and then i can use this to see which colliders were in the collision?
yeah alright, thanks a lot
I'm have to make logic for possible legal moves for chess pieces.
Currently I've made the logic in one file only and assigned that script to every chess piece. I've been told to follow good coding practice and write clean code.
Now, im confused should i keep it as it is only (every logic in 1 file) as its easier to assign one file to any piece and there's no issue of wrong file assigned.
Or
Second, i should put different logics in different scripts and assign it to individual pieces as per their names (like a rook script for rook, a queen script for queen.... And so on)
Or
Third, i should make different scripts for each individual pieces but connect them through one common script, that will call these scripts after a series of if statements using tags. This way also I'll have to assign only 1 script to all pieces.
What should be the best practice?
The standard for a solo dev is pretty much just calling .Instance everytime. This really is a micro optimization, events would work but then you also have the issue that everything needs to subscribe and unsubscribe to an event. There surely wont be any noticeable performance difference. You could apply a pattern like a service locator
Thank you! If the performance difference will be a micro one that I'll just do what you said indeed. I'm gonna read about a service locator too, tho π€
is it possible to see custom classes in the editor: but that inherit from a custom class?
for example in my mono behaviour script I have:
IBaseClass myClass;
for example in start:
myClass = new InheritingClass;
how would I edit public fields of myClass from the editor?
for debug only.
Architecture for a game like chess can be really simple if you want to make it only in line with the existing rules. it's really quite easy to just place all your logic in 1 file, give each Piece an enum saying which piece it is, then doing some logic based on that. But if you want clean code, this isnt easy to extend. For example if you wanted to introduce a new piece, suddenly you have to edit this script again. If a piece suddenly changes movement, you need to edit the script again. This script would essentially never be complete. In terms of clean architecture, I'd say it's pretty sufficient to have a base Piece abstract class (or make this an interface but dragging in inspector will require custom editor functionality), then you create child classes which implement methods like how it can move given a certain board.
Make the class Serializable
does not seem to work for inherited classes
I made both the inheriting class and the base class serializable
iirc you need the attribute
That's not the issue, you declared the type as the base class
yea
Thus you only have access to stuff on the base class
the only way to do this is fairly round about and will need a custom editor
but its possible with SerializeReference
Abstract?
yea I thought it may come to this
SerializeReference fully supports polymorphism unlike SerializeField
but you will not get automatic creation from the editor so will need to handle that via editor script
I will try it, thanks
that's fine
it even supports interface types
but you editor logic will need to create the objects yourself
There's packages around to help for that
oh ye thats the attribute, forgot the name
yea already doing that
yeah i always just made my own logic, i dont lean on much from the store at all
ok it seems to work, but whenever I enter play mode it entirely disappears
Clean code isn't universal it's just an opinion and if you ask 100 programmers they would differ on a certain practice and there is wisdom in knowing when to use it or not. Seems overengineering in your case but if you insist the way Id do it is define the types of chess pieces and have some sort of IChessPiece they all inherit from so someone else can understand what it does without looking at the implementation just the interface. Especially if you have a epic supermethod with hundreds of if or cases. This mindset is very similar to the book code complete 1/2 about clean code from microsoft, where the authors considered exceptions to every rule they state
Ive found mackysofts serialize references pretty good and I think vertx had something worthwhile
in vertx I trust
the interface would enable dependency injection as well and testing outside of unity if that is easier for me (sometimes is for me especially when importing new assets and waiting hours, I can just test the code in a winforms project while unity does whatever/mine bitcoins...)
But in the end I just dont serialize by abstractions even though interfaces is probably a real miss for unity not developing more fore
i just wish you could drag in UnityEngine.Objects via interface types, with out of the box unity
absolutely
does not seem to work for me. really odd, I followed their example too
at first it appears in the editor empty
on playmode it just entirely disappears
oh
speaking of which how do you manage it when you have an itemcollection with items but some asset wants you to fill their catalog with their own item class ?
flywheel or interface pattern ?
this is a MB or a SO or something
or you could delete the class of yours and start over ?
SerializeReference is more for regular C# classes @light wraith
i assumed that was your case
yea that is my case
not monobehaviour at all
I hold a regular C# class as a variable on a monobehaviour class.
I would like to edit values on that regular class from the inspector
usually it is possible with just placing [System.Serializable] on the class
but in this case, I have an [SerializeReference] IMyBaseClass (= new MyInheritingClass)
so with SerializeReference it will show up totally blank first
you need to construct the object via code first
yes
then you can see it in the inspector
in the mono behaviour class:
and on start()
this is movement state
and normal state:
strange
yea
mine is abstract but in the docs it says it supports
is all i did, then i ran the context menu thing to create the data
then i was able to edit in the inspector and have it show up as changes in diff
ok, I will try with your example
you will notice in your diffs in git, it shows up very differently then a regular serilize field
will warn this approach is fragile to type name changes and refactoring
@thin aurora I'm still having troubles implementing that GetContacts method, where do i get the collision from?
would come from your OnCollisionEnter or a physics method call
@quaint rock am I doing it right?
it does show up in inspector all the time, but empty, float test does not appear.
even after start?
toss [ContextMenu] on so you can invoke it in the editor
the example i gave was just a quick and dirty test, but how it showing right away for me
normally in cases like this when its done i will create a popup menu in the edtior scripting that creates the object of the right type and stores it in my base type or interface type
well thats the problem, the script i have is on an empty object in the middle of the scene. I need to check collisions between rooms that are spawned using this script around the scene
i dont have context but think i would use Physics.OverlapBox
with my bounding boxes
you mean to ok()?
no to create the data, the one that calls new and constructs
what is going on
i just want to be able to spawn rooms with various shapes and check if their hitboxes overlap so I don't spawn them inside of one another. The bounding box is a box, that would create problems if the rooms aren't squares right?
I added it to ok() and it now works π
I am so confused!
but it doesn't even show the function
split those types of mesh into different cube sections, and run overlapbox
I can edit the value through the inspector
You don't get the collission
The method collects all active colliders colliding with the calling collider component you call GetContacts from
All you need to do is pass an empty array or list and it will fill with references to the other collider components
Note in the case of an array you need it to be big enough. If you have a size of 10 it returns 10 max, or less. A list will be resized so that might be better.
don't you need a collision to call the method on?
yeah i get that much, i just dont know where to get the collision to call from
I believe you get the source collider component and this should have the GetContacts method
That would be whatever you need to check is being collider against
What is it exactly you want to know in this case?
would just keep it simple if all you want to do is query for colliders in a area just use something like this
https://docs.unity3d.com/ScriptReference/Physics.OverlapBoxNonAlloc.html
like how do i take an object with a MeshCollider and and it "is this mesh collider currently colliding with something?"
You would take the object with the MeshCollider and call GetContacts
And if I read the wiki correct it should returns a collection of references to whatever the mesh collider is colliding with
Collider does not have a GetContacts method
Or do what Passerby mentioned, that works the same basically
.... The page is about a collision, not a collider
Well then
yeah, thats what i was having trouble with
I guess I totally misread this then, I thought it mentioned a collider
but this should work, thank you
Actually, it does mention a collider
I initially read this page https://docs.unity3d.com/ScriptReference/Collider2D.GetContacts.html
Why is this different? π€
box2D vs physx
yeah messes me up sometimes, some features are not available in the other n vice versa
yeah, you need a collision, but since the script is on an empty object and the GameObjects are stored inside of a graph class, inside of a node class and inside of a room class i didnt think i could use the OnCollisionEnter method
it works with HitInfo objects when you use the raycast or overlap methods
There's contactpoints
Which you dont need collision
Oh no im think of closest point
Was using it earlier for some ricochet logic without a rb
WHY DOES ANY UNITY METHODS like awake, update MAY STOP WORKING ON ALL UNITY EDITOR VERSIONS?
a
Dont crosspost, why even think this would be a general or advanced issue
Awake and Update not awake and update
wait but this wont work, i need collisions, not colliders, i can get those easily
Rb is for collisions
i dont know your usecase never seen the original question
Rb?
Otherwise you need to calculate the first point of contact
yeah, i have rooms with colliders and i need to check if any of the colliders overlap
Overlap sphere is the answer
can that find collisions?
It finds colliders
but i have colliders, i need collisions
if you just need to know hte objects what i posted is enough
i have the objects
if you need each contact point then you would need a collider to create collsion events with
i need collisions
You check colliders. Collisional stuff is more specific to rigidbodies
what do you need the collisions for?
i feel like we have not heard the whole extent of what you want to accomplish
lets say i want a tree like structure out of rooms, when i spawn a room, i need to check that this new room doesnt overlap with any other room, if it does, remove it and try again
every new room is spawned from a door on a previous room
so i assumed you wanted to check a volume of space
if you want to do it via colliders you already got i would loop through all of those colliders and work with them methods on them
if i spawn a new room somewhere around these 3 rooms i need it to not overlap the other ones
or do like bounding box checks via the OverlapBox
which will tell you if other colliders overlap a space
yeah but the problem is, my rooms arent just squares
what type of colldiers are used
yeah but, having colliders, how do i check their collisions? I couldnt find any method that would be helpful
just mesh for now
so without first spawning things this will be hard to check for
what i would do would be looping through the colldiers to get the bounding box for each one
then use overlap methods
yeah but my problem with the bounding box is that, well its a box
so it takes the spaces around the room that could possibly be used
but in reality are you describing a complex shape like that as 1 collider
or would that be 2 or more
every room is a single object
thus you can check that one by one
how do you mean?
so that is really ineffecient since you have 1 massive non convex collider per room?
Like i said split it into different cubes
I already see that room can be 2 Rectangle colliders
i mean the rooms are created out of 3x3m prefabs technically
like i have done similar feature before in a game i am currently working on
but it works since each wall is a collider, each rectangle part of the floor is a collider etc
since colliders work best as convex shapes, and i tend to not model 1 room whole sale but build it from modular parts
and sometimes even the modular parts have a few colliders if they need to describe a shape like a arch so i can have multiple convex wedge shapes instead of 1 concave arch
some of the reason i approach it this way is for the scripting side, and some of it is simple for optimization and workflow and wanting to stay convex everywhere
okay so lets say each room would be made out of the 3x3m tiles, how would i go about this then?
When you put this mesh type, check this bounding box, solved
i might just do that, how would i then check collisions of bounding boxes?
just get center, calculate top left and bottom right corner and check with all the other bounding boxes? Or is there some smarter way to go about it
Though you can always use more than one box. I assume these are prefabs anyway so customize the bounds
how do i do that? I looked to see if objects have a bounding box component, but i couldnt see one
Renderers have a bounds property
colliders have them too
yeah i noticed that in scripting, cant see it in Unity though
in the case of tile based games, i have also just in a other object just defined waht shape something is manually on the grid so i could use that to check if its going to overlap anything
like there are so many ways to do this
thing is, this isnt supposed to be on a grid
i was just saying that is a other way based on the usecase
yeah, alright
think I'll just create my own Bounds class that works well with my other classes and give up on the idea that the bounds aren't just rectangular
Playing Videos in a WebGL build seems to no longer be working. I tried the VideoPlayer approach with the video file being in the StreamingAssets folder. It works in the editor but in a WebGL build only the sound plays, the video stays black.
Anybody here have an idea why that is?
videoPlayer.errorReceived += VideoPlayer_errorReceived;
string streamingPath = System.IO.Path.Combine(Application.streamingAssetsPath, path);
errorText.text = streamingPath;
videoPlayer.url = streamingPath;
videoPlayer.Play();
```I get no errors either.
I've got this effect for when a player touches the screen - I emit particles from the touch location. I move it around and set the emission rate to 100/0 depending on if the player is touching the screen. Works great except when they first touch - it plays a particle or two from the last location of the game object.
I'm definitely moving the object before setting the emission rate to 100 but I imagine that because it's in the same frame, it can emit a particle at the old location.
Any ideas how I can get partcles to not emit for one frame easily?
(sometimes there's one particle emitted from the wrong place)
i feel like iβve had this issue before, but I donβt recall the answer. did you try making sure the particle effect gameobject is in the right position before turning it on?
or is it not on a gameobject at the cursor?
so... i'm not actually turning the GO on/off, just setting the emission rate.. because i want particles to live after the emitter stops
lemme paste some code, sec
i think i normally use a trigger event in the vfx
private void StartTouchParticles()
{
ParticleSystem.EmissionModule em = TouchParticles.emission;
em.rateOverTime = 100;
}
private void StopTouchParticles()
{
ParticleSystem.EmissionModule em = TouchParticles.emission;
em.rateOverTime = 0;
}
public void OnDrag(PointerEventData eventData)
{
if (!_isDragging) return;
TouchParticles.transform.position = eventData.position;
}
public void OnPointerUp(PointerEventData eventData)
{
StopTouchParticles();
if (!_isDragging) return;
}
public void OnPointerDown(PointerEventData eventData)
{
TouchParticles.transform.position = eventData.position;
StartTouchParticles();
}
that should be all the relevant stuff
look at the VFX graph
how are you making your particles?
just a vanilla particlesystem
do you not have a VFX graph?
Unity.ParticleSystem or whatever
i mean, I have a library that's flattening the particles into UI meshes but that should be irrelevant for this
.... maybe
first try turning off play on awake
i suspect that might be emitting something, that then gets paused
shouldn't matter, since the GO is always on
like i never call play() stop() or any of the ParticleSystem methods to start/stop the system .. the only thing i do is change the emission rate
idk much here. but i suspect invoking play/start manually is the way
i can't recall though - i think stopping the system kills the "in flight" particles
you are probably right. sorry, iβm not well versed in this one. you will need help from someone else
all good.. open to any ideas TBH.. can't seem to figure it out, short of making this more complicated than it needs to be with a coroutine that sets the emission rate a few frames later
Actually, after rethinking this whole situation I've come to a conclusion that every single delegate in my 'Manager' could be made static, thus removing the need to subscribe to a singleton instance to trigger events
This is how I do it, although some people frown on it. It's worked for me
Oh? why do they frown on it tho?
public class PlayerManager : ReloadableManager
{
public static event Action<MinigameDefinition> StartedNewMinigame; // UI subscribes to "domain logic" events and animates them accordingly
public static int HighestLevelCompleted => Instance._highestLevelCompletedCached; // simple data points, accessible anywhere
public static void SubtractLife() => Instance.SubtractLifeInternal(); // "global" methods contained within the singleton
// and the boilerplate
private static PlayerManager instance;
private static PlayerManager Instance => instance == null ? FindFirstObjectByType<PlayerManager>() : instance;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
if (_player == null) LoadPlayerInternal();
_isInitialized = true;
}
}
race conditions, tight coupling, etc
I like it because it's convenient - I put all my singletons in a single DDOL in my loading scene, and then all the functionality in my entire app is available without any fussing about instantiating and/or getting references to these game logic objects
the bulk of my codebase is rendering/ui anyway
it does sound convenient. as I see it, you need non-static events when you need to listen for events from a specific instance of the class, and maybe not listen to another instance? If you don't need that, or if you're gonna have only one instance of this class (if it's a singleton) then... any events fired from it... will be fired from only one place? right?
i don't have any non-static instances that emit events.. that's just not a pattern i really need
so making these events in this scenario non-static only puts a burden on you to subscribe to a specific instance and figure out the script execution order as well
I use events really heavily since it bridges "domain" and "view" really nicely
The fun thing about static events is you can always just manually pass in the source instance if you want as well
my 99% use case is "something happens that requires UI, so emit an event" and all the UI stuff that cares about it subscribes/unsubs in OnEnable/OnDisable
yeah - i haven't needed it (i almost always just send null in the obj sender pattern) but it's there if you do
that is absolutely right
so the use case for non-static events is really limited to when you need a lot of different listeners listening to a lot of different specific instances of things.
For example if you had 100 enemies each with their own health bars emitting HealthChanged events. You wouldn't want them all to say if (source == theOneICareAbout), you'd just subscribe them each to the appropriate instance event
public class GoalUpdatedEventArgs : EventArgs
{
// bunch of data
}
public class GameManager
{
public static event EventHandler<GoalUpdatedEventArgs> GoalUpdated;
private void SomeMethodThatDoesShit()
{
GoalUpdatedEventArgs args = new()
{
// blah blah blah
};
GoalUpdated?.Invoke(null, args);
}
}
EventHandler.Invoke(object sender, T args)
i think you're "not supposed" to use this as the first parameter in static classes but.. if you need to, you can
Unsolicited advice - but I recommend not using the EventHandler pattern in Unity
Unecessary overhead/GC allocation
oh? why's that? i was just starting to move to it
interesting.. just instead of vanilla delegates?
Just define your own delegate type!
public delegate void GoalUpdatedHandler(Enemy source, int myParam1, int myParam2);```
i've lately been migrating my codebases over to that pattern, I wasn't aware of GC overhead
yeah, well, that's close to what I did (I used Action<T> though with a <T> that had all the parameters)
almost all of my delegates are Actions, so I rarely need to define my own
using object source isn't type safe and could involve boxing struct types
And allocating a new MyEventArgs instance is GC allocation if it's a class
It's because of the new
yeah that's equivalent
but if you have a delegate used a lot that has non void return type, then defining it is a good idea
You never need to really, I just prefer to as personal preference
otherwise my delegates started to get hairy and confusing
public static event Action<int, int, float, string, (Color start, Color end)> TileUpgraded;
this is an actual event in my codebase that I haven't migrated to the "new" way yet
because I like typing HealthChangedHandler instead of Action<Unit, int, int>, it's more clear
obviously the big problem here is not having a T to hold all those parameters
yeah this is why i prefer named delegates
But I recognize the convenience of Action where appropriate
obviously one is easier to read
public static event TileMovedHandler TileMoved;
yeah i only use Action for 0 to 2 args
although I haven't found a good "normal" place to hold event arg classes
if its more complicated i will define a proper delegate type
I kinda hate littering up other files with them, but then they feel too "small" to each have their own file
Even without defining the delegate first, you could put the 2nd one in a struct all the same
define a delegate in the scope of a class that uses it a lot
I've gone back and forth on the struct thing because of the copying overhead.. I mean, I'm using a lot of events in my codebases
what do you mean littering
too much shit
just put it in the scope its needed
only stuff in a class cares about that delegate type make it there
yeah, I suppose i could put it inside the scope.. didn't htink of that
same goes for structs and enums and stuff
Its nice if you are unsure about something changing. Like my DamageInfo struct in the future may add more details, but I dont wanna refactor 20 classes to adjust for this
ie here's my .. GameManager file, collapsed a bit:
i very commonly have a bunch of supporting types defined inside the scope of a larger type
GoalUpdated, TileDestroyed, TileMoved events are all like... 4 lines.. making a file for each of them seemed silly
didn't think to put them inside GameManager
you want to put them in the scope of something meaningful
like one of my SO's has really complex nested data defined in it, i literally have 2 enums and 8 structs defined inside of it and a delegate
so those dont litter the whole namespace or assembly
reping my OP since the singleton conversation hijacked it π
Well, this was unexpected! Type 'UnityEngine.Color' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable. I'm using BinaryFormatter to create a custom save file. Do I really need to create a whole new custom struct, and populate it at serialize-time just to save a Color?
Unity's notion of "serializable" is distinct from C#'s notion of "serializable", yeah
I'm not sure if there's a way to convince BinaryFormatter that the type is fine to serialize
also, you're about to be warned about BinaryFormatter π
Obligatory "please don't use BinaryFormatter" comment!
Yeah it's formatter
yeah, I mean I CAN create a custom struct marker with [System.Serializable].. just gonna be a pain.
You know me so well Fen
I clicked on the warning on that page and it took me to one written in Spanish
if anyone wants to inject code into my save game files, they are welcome to π
hello! i have a question, how can i make a custom editor where i hide and show variables based on the toggle? i've tried to do smth but it didnt really do what it was supposed to lol, also am using custom list's(variables inside lists), should i send the full code here?
Well it's not _your computer _ that would be at risk, it's your customers'
Anyway I'll drop it π
use GUI toggle or sorts
That's an awful way to think about it
Why not just use the better option? It's exactly as easy
just a home project. But I AM curious about it ... my game open the file and fills data structs.. how COULD injected code get executed with that?
i did but the list gets unlisted lol like the stuff become variables
like this you mean you wanted right
https://docs.unity3d.com/ScriptReference/EditorGUILayout.Toggle.html
this is what i want to make
but the options piece to hide or show the top or bottom variables(bottom being isremu and text_) and true for showing the anwser_options array
you'll need to make a custom Editor or custom property drawer to do that. Check the bool, then do or dont display the following controls.
for a more extreme example, read up on python's pickle library
it can execute completely arbitrary code when it deserializes data
BinaryFormatter is more constrained: you cannot trivially make a blob of data that runs completely arbitrary code
i did that then this is what i get
https://github.com/pwntester/ysoserial.net has a big collection of BinaryFormatter vulnerabilities
it's pretty cool: it's a lot like building a ROP exploit out of small code gadgets
so it uses a driver installed on the system? interesting. But wouldn't we have to count the system as ALREADY comprimised if such a driver is on it?
hey guys had a question about grids / a* pathfinding. If i'm doing pathfinding jobs, do you guys recommend creating a new grid array for each pathfinding job, to store parent nodes correctly?
or have one master grid?
this doesn't involve "drivers" at all
it's abusing existing libraries to cause things to happen to your system when you deserialize data
extreme example: if you have a class that deletes all of your files when you construct it, then deserializing data that includes an instance of that class will rm rf you
guess I misunderstood "The main driver program takes a user-specified command and wraps it in the user-specified gadget chain, then serializes these objects to stdout." But regardless, this special code/class must already be on the system, right?
the problem is that the special code is from standard .NET libraries
it's not really special at all
That's the idea of these "gadget"-based attacks
return-oriented programming takes small pieces of code from a vulnerable program and strings them together in a way that winds up making the program do something evil
interesting stuff, thanks again for that link Fen, I'm still not quite getting it yet, 'cept the running the constructor stuff- THAT makes sense. I'll have check that out link in more detail.. but for now- I just need to serialize a UnityEngine.Color.
I believe the core problem with BinaryFormatter is that you can't say "I want to deserialize a Widget": it just does whatever the binary data tells it to do.
well said
I currently just use Json.NET. I've been thinking about switching to BSON (which is roughly just JSON, but with binary data instead of printable characters)
Json.NET has a pretty major advantage here too -- you can write custom converters to deal with this kind of thing
so when it finds a UnityEngine.Color, you can tell it "oh, just write four floats"
You don't actually have to create a "serializable color" type in that case
Will check it out. That system handle references to objects properly? (by which I mean... I have say 4 referencs to an object, will it save it only once and create the appropriate references at deserialize time?
how can i get OnCollision functions working on objects with Mesh colliders? I dont want to make the mesh collider convex
You can't put a rigidbody on a non-convex mesh collider.
However, you can put a rigidbody on something that hits a non-convex mesh collider
yeah I'm checking room collisions, both of them have mesh colliders. I guess ill just make them convex, check collisions and make them not convex
If you're talking about Unity objects, then definitely not -- they need to be created correctly. I haven't made a "save game" system yet that requires serialization of in-world objects yet
More generally, I'm also not really sure -- I've stuck to serializing things like settings, statistics, and configurations so far. Much more tree-like.
It's something I am going to have to figure out at some point; it just hasn't happened yet
I would try to wrap them in primitive colliders.
well this doesnt work so ill have to do that yeah
Is this for level generation?
yeah, checking if a generated room intersects previous rooms
perhaps you could use MeshRenderer.bounds and check if they overlap? https://docs.unity3d.com/ScriptReference/Renderer-bounds.html https://docs.unity3d.com/ScriptReference/Bounds.Intersects.html
^ note this uses a box that encompasses the entire mesh, meaning 2 L shaped rooms (concave) could have the bounds overlap, even though the meshes themselves might not overlap.
Hey does anyone know how i could recreate this boost effect for Just Shapes & Beats, with the little expanding circle getting a thinner outline as it grows, using a ParticleSystem on Unity 5.6? Thanks a lot :D
yeah i thought this would be a problem but i kind of give up on that idea, ill just use the bounding box, thanks
Why on diesel Soviet version of Unity
Anyway just kinda looks like a particle system with some masking effect
I made a script that generates new waypoints if my Ai gets stuck on a wall (the scene is dynamic)
at line 143
i want to choose the point with the smallest distance, how can i do that
keep a var for the minDistance seen and for the object that got it
each time something has a smaller distance assign both
see what you got at the end of the loop
k thanks i'll try searching for that
If you saw my question, I just don't know how to read. My problem is fixed !
can't seem to find any Masking option in the particlesystem renderer, i think it has been added in version 2017? or maybe i'm doing something wrong
Hello! I was looking for info on creating a multiplayer game using Netcode for Gameobjects with a mix of ECS for the terrain generation.
However, when I install both, i get an error since there seems to be a conflict with the libraries. Has anyone found a soluition for this?
well
Netcode for Entities is a thing
ECS is not compatible with GameObjects
I know, however, I specifically wanted to use ECS for the terrain and nothing more. I didn't want to fall into ECS as a whole
not possible then?
like... to generate the terrain?
There are some bridges
or what?
Yeah, just the terrain
the problem isn't using one of the technologies, its more on having both packages NGO and ECS in the same project
just use DOTS for terrain then
you get some benefits by using Jobs for example if you want to split it on different threads
by terrain you mean just the terrain data, or deformations, objects on it?
if just data you can run generation in jobs, no ECS needed, but i think that even if you need ECS you can keep ECS world and copy entity data to the GO world
alright, ill focus on the DOTS aspect instead of ECS. Thanks @ashen yoke @rigid island
btw Dots is the whole stack including ecs.
iirc unity does have some bridging for that (ecs to gameobjects) now that i think about it
but yeah I'd learn Jobs first
Indeed. Ill focus terrain generation more on the jobs side
Yep! I use Jobs in games that aren't Entities-based at all.
combined with Burst, you can do a lot of work very quickly
anyone got an idea what's the best design option for this?
I'm a bit confused as I've seen people using a single grid for mulitple a* jobs at the same time, but wouldn't that cause the parent nodes to collide?
what do you mean by collide?
so if i'm using a 2d array and to pathfinding jobs use the same node inside that array, they will end up overriding each others parent
this is my node class
i'm using a*
not sure what you mean, you create structures to compute the path, minheap, queues etc that will be cleared once the path is done, you dont need to modify the actual grid
ah so just store a list/struct instead of using the parent of the node
there are several ways to do it
you can store a giant 2D array to get fast access of matrix to node
Don't store A* data in the actual grid tile
The different A* operations will be fighting over that data.
I use Djikstra's in one place and A* in another. In both, I create a dictionary to map each node to its parent.
they aren't jobified, but..maybe I should try that (:
i'll probably end up doing something similar
Djikstra's looks awesome too, i like the way rimworld do it with regions
probably going to implement something similar
I use Djikstra's for a search problem where I have no way to come up with a heuristic
i'm pathfinding over a graph with completely arbitrary connectivity and with no hints about how close I am to the goal
I use A* for goal-oriented action planning
in that case, I can estimate how close I am to the goal based on how many things still need to be accomplished
ah that makes senses. I'm only looking at simple movement at the moment
Movement is great for A* because you have a good heuristic
(the distance to the goal)
yeah it's pretty good but with grids, it was having issues. i'm going to end up splitting the map up into regions and using Djikstra for bigger distances
hierarchical pathfinding can be way more efficient
will also help with use case where a pathfinding goal is innacessible like you mentioned
never heard of it, i'll look into it. ty
that's what you're doing :p
split the world into regions
pathfind from region to region, then within a region
ooh lol. I've not implemented it yet, just thought it looked great
https://www.youtube.com/watch?v=RMBQn_sg7DA&t=6s basically this
My game design book: http://www.amazon.com/gp/product/1449337937
Twitter: https://twitter.com/tynansylvester
RimWorld Alpha 4: https://www.youtube.com/watch?v=wusy3Z8JKkY
The game: http://rimworldgame.com
My blog: http://tynansylvester.com
I'm trying to add the ability to link images/textures to a graph element in a custom node editor, does anyone know any good reference code/tutorials for that?
I've dug through the documentation and found input node features for stuff like how Shader Graph handles 2D Texture inputs, but that relies on a centralized property list, and I want to make something that links more individually on a node to node basis.
I've stumbled into a problem with TextMeshPro where if I pass a regular color into the font atlas material - it gets effed because it is an HDR color while I am working with regular colors in my project. I want to change the font color globally, hence why I am altering the material directly, however either because it is HDR, or because TMP Vertex Color property SOMEHOW affects it - the resulting color is always wrong, paler and brighter.
I understand that if I alter both Vertex Color and Face Color - it will show me the correct color, but I don't want to alter Vertex Color of every goddamn TMP field in my project, it's stupid!
For now I've removed [HDR] from all the colors directly in the shader. Colors still show up wrong in the editor, but in the game view they are fine. I don't know why this problem exists, or if this is a problem at all, but I hate this solution and everything about this issue. If anyone faced such issues with TMP and solved them - I'd like to know how.
There's nothing special about it being an "HDR color"
all that does is allow you to pick colors with R/G/B values greater than 1
A color that you've cranked up past 100% intensity can start to look washed out, depending on the render pipeline and tonemapping settings
a super bright color in the HDRP will turn white with the ACES tonemapping setting, for example
With OnCollisionEnter2D( Collision2D otherObjectsCollision), i can get the contact point and normal of the other object colliding with the game object with the OnCollision method.
But how can I get the game objects contact point and normal with that other object?
GetContacts
Hey guys!
Here is a video of a game that has an interaction system I am trying to model
Two handed grab with an offset
Just think of how you would grab a gun like that, one hand on the grip, and one hand off to the side where the foregrip is
I've been stuck on this for days and would really appreciate if a quaternion wizard came in to help.
Thanks!
I am currently trying and failing to make a general purpose interaction system. I'm able to get it sort of working, but the players hitbox gets in the way of the raycast when you start looking downwards. This is my current code: ```cs
void Update() {
RaycastHit hit;
int playerLayer = transform.root.gameObject.layer;
int layerMask = ~(1 << playerLayer);
bool hitInteractable = Physics.Raycast(interactionSource.position, interactionSource.forward, out hit, interactionRange, layerMask);
if (hitInteractable)
{
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null)
{
interactionPromptUI.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
interactable.Interact();
}
}
else
{
interactionPromptUI.SetActive(false);
}
}
else
{
interactionPromptUI.SetActive(false);
}
}``` This script is attached to the playerCamera, which is a child of the playerCapsule
Also not happy with how messy the code currently feels
Instantly realized I didn't actually set the players layer to anything different so I feel a bit dumb, though I'd like this system to work in multiplayer down the road anyways so this solution isn't future proof, as currently youd be able to interact with stuff through another player
is this first person or 3rd person? i assume 3rd. Maybe regardless you could find a way to start the raycast inside the player so it does not detect the player. Could play around with where the interactionSource is depending on how the player is looking.
Otherwise you could start a 2nd raycast if the first one hit your own collider. There is also stuff like RaycastNonAlloc but you would need a 2nd raycast anyways or some comparison to see which object is closest
First
The raycast starts from the camera which is inside the player
Actually now that you said that I checked and the camera was only partially in the player
it shouldnt be hitting the player then at all
FromTo guarantees that From will go to To, but doesn't give you very much control over the complete orientation. Imagine you hold your hands as if they were aiming a sniper at a target. You know if there were a sniper in your hands it would be pointed at the target. But that sniper could be upside down with your pinkie on the trigger or on its side, and in fact could be rotated any angle about that axis. Therefore making From point at something is not enough.
Not 100% sure but suspect this could be leading to the behaviour in ur test.
Will think harder on a solution.
hello there i am trying to make a grounded check in unity 2d after a few months of not using unity but for some reason it changes to grounded then stays like true.
this is my code grounded = Physics2D.Raycast(transform.position,Vector2.down,Distance,LayerMask.NameToLayer("ground"));
What is the distance?
And where do you check the grounded state?
Ok hmm. Good for both
to be clear, it's false at the start, goes to true, then can never come back?
yes
And only the ground has the ground layer?
yes everything else is defult
Oh daaang
ahhh
I never use NameToLayer so I always forget
so do i have to difine a layer mask i have never done that before
layermasks got me for like a week before i figured it out
I provide all the solutions on that page
ok ill test it out thanks for the help
ok so i initialized the layermask with... public LayerMask layermask then changed my code to be grounded = Physics2D.Raycast(transform.position,Vector2.down,Distance,layerMask); now grounded doesn't change from false btw i did remember to change it in the inspector
Does anyone know how to have textures/sprites linked within nodes in a custom graph view?
I've got foldouts/input + output ports for linking but I can't seem to find anything in the documentation that refers to other 'bindable elements'
I have the data structure to store the image/anchor positions I need for the system I'm working on but I'm not sure how to make the graph view draw an image/texture field into a node.
create a visual element and set its background to the sprite/texture?
or use a preview container
@full oar Don't cross-post
womp womp
You know what's weird, the rgb values I pass from color to TMP HDR color are correct, however when I switch to HSV mode - values are different for HDR, even if intensity does not move from 0 during the exchange/conversion. It must not be the HDR problem, but a TextMeshPro problem with how it... I dunno... blends vertex color and face color values? It's weird and I don't get it.
I don't like the transform.rotation *= line. That's probably what's causing the wild spinning
note that the "intensity" value you see in the color picker doesn't actually exist in the Color struct
it's just a scaling factor for the R/G/B values it's showing you
I forget the base, but if the color picker is showing red = 0.5 and an intensity of 10, then the actual red value is 0.5 * base^10
Hey guys, I am trying to make a 3d platformer game and I got the player controls by the standard third person controller assets, I want to make a rotating asset I have shown such that it makes the player slip, right now as the player is based on character controller, it does not have simulated physics that allow that
for my physics based grab system what forcemode do i want to have when trying to get it to a target position?
probably a continuous force
and one that depends on the mass of the object
so, the defualt force mode : ForceMode.Force
You haven't defined the problem well enough for an answer. Technically any force mode can work provided you do the appropriate calcultions. But you haven't explained what the behavior should be
It depends on how "snappy" you want this to be
you could do something like a smooth damp or just do a teleport if you want immediate change in position
if you want to grab something and have it interact with other physics body then sure check this out:
https://discussions.unity.com/t/difference-between-forcemode-force-acceleration-impulse-velocitychange/103470/4
##History Lesson (not really) Ok, so more than a year later Iβve had the need to come back and attempt to fully understand this problem (as I never really understood what the differences were). After staring at the formulae for a long time and not really getting anywhere, I decided to stare at the page linked by @jchangxu (thanks btw!). After a...
alright
Anyways I need serious help, my code is becoming spaghetti. I want to ask about how to clean up Coroutines when they are suddenly interupted during a phase. Currently the WallCling would interupt the jump and I would need to reset the variables depending on the phase of coroutine. I have considered making functions for each phase but that would quadruple the codes' length.
Here's my code: https://paste.ofcode.org/77TsxASkNnH4rRNMxUcaPx
Btw, you could also give me some recommendations to organize code better
your link seems broken?
I want to set all of the knots in a Spline. It looks like calling SetKnot winds up doing a lot of extra work per call -- it's dirtying the spline and doing some other work every time I call it
There's a SetKnotNoNotify method that skips this. I'm planning to just do this:
for (int i = 0; i < knots; ++i) {
// calculate some stuff
if (i < knots - 1)
spline.SetKnotNoNotify(...);
else
spline.SetKnot(...);
}
I don't know if this is going to cause some weird internal problems for the spline
I'm just going to
but I'm curious if I'm missing something here
is a virtual function like an abstract function but you don't have to override it?
virtual function has an implementation already, that you can choose to use or not use
ah ok
cool
you can also do
public override void DoX() {
base.DoX();
//My own DoX
}
nice
Hi, I'm trying to use a simple grab and drop object script and I'm having a problem with it. If I look down with the object on my hand the object will collide with the player and send him backwards.
How could I disable the collider only between the player and the object when it is in the player's hand?
oh that is perfect thank you
note that this disables ALL physics interactions, including force, callbacks, etc. If you need to block just force or just callbacks, you can set layer overrides.
i uh, forgot to read
although, this generates garbage...
the problem is that I can't call SetDirty -- it's an internal method
this breaks the spline; it doesn't update the spline curve properly
i guess it's time to Embed That Package (tm)
wow, this is a lot faster -- like, unreasonably faster
i have to triple-check this; i must be messing up the benchmark
oh, I had deep profile on, which was probably unfairly penalizing the one-by-one approach
This is still an enormous difference. This can't be right...
I created 16 4-knot splines and have a script that either:
- calls
SetKnotonce per knot - makes a list and assigns it to
Knots
SetKnot is taking about 3ms. Assigning to Knots is taking 0.15ms (and creates a lot of garbage, since it's making entirely new lists in there)
Both versions are working just fine..
Looks like SplineCacheUtility -- an editor-only class -- is responsible; it tries to update some cached data instead of just throwing it all out
So it's not a runtime problem, but it sure is an editor problem...
hello I keep having really weird problem
so I import strings from file and then write them out
they are loaded okay
but when writing them out they behave weirdly
well only the first letter
first letters behave like this:
sentence1[sentence1]
sentence2[sentence1]
sentence3[sentence2]
and so on
but the rest of the sentence and words are alright
i found one solution to this
copy the object, remove the original and it works
but just once
on other runs (and even builds it breaks again)
I am sending video and code snippet below
the weird thing is that it only breaks on some objects
even if they are from the same prefab
i will share all related scripts
there are like 3 at work
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use a paste site for them
thank you
WriteOutSentences: https://paste.ofcode.org/k9fAnYH8e8XGqdxZA8QsTH
WriteTextProlog: https://paste.ofcode.org/NSy28gXzFFz6nzfXRPxhEA
InteractTextPrologWritingSentences: https://paste.ofcode.org/UB6fV8VJhmXZaxxh3SMRF4
WritingGameplayProlog: https://paste.ofcode.org/UZW4CYRewEKSmDgJcfSLJP
ControlWordsProlog: https://paste.ofcode.org/mcBCxAFNTVWqNZdchqJSgh
the last two are just the behavior of the write outs
WriteOutSentences load text from file
and WriteTextProlog prints sentences into text area
It's rare but I sometimes fall through the one-way platform effector. Are there parameters I can mess with (like maybe the collider size?) that could make this more consistent?
how do i get the magnitude of a vector3
k im trying to add it to another vector3
can't add a float to a Vector3
could add "new Vector3(float, float, float)" if you want
or only to whatever component you care about like "var xOffset = new Vector3(otherVec.magnitude, 0.0f, 0.0f);"
or v3 = v3 + (v3.normalized * otherVec.magnitude)
what are you trying to accomplish here?
Sorry, I don't need to draw the image itself to the node, I have a data structure to store images for the node, but I am trying to find a way to display/draw the linking/reference portion of this behavior to a node.
I need an image anchor to embed a dropdown for an enumeration that tracks anchor position, and link/reference to an image in the project.
I wound up embedding the Splines package and:
- adding a
SetKnotsmethod that reuses the old BezierKnots and MetaData lists - getting rid of a ton of garbage allocation by not using
IEnumerablein one place (manually iterating over four lists instead of using a method that iterates over them for you) and by avoiding aSelectin another place (which was also super simple)
0 GC allocated per SetKnots call! It runs way better in the editor, and it also runs better than calling SetKnot repeatedly in the build.
Most importantly, it still appears to work correctly, too π
Hello everyone! I'm currently working on developing a visual asset for Unity aimed at managing JSONs in a more intuitive manner. But i've found a little problem...
I'm seeking an efficient method to handle custom data types within my asset. Specifically, I want to enable users to seamlessly add their own data types. For instance, consider a scenario where a user wishes to introduce a data type named 'WeaponType' with various values such as 'Rifle', 'Pistol', 'Shotgun', and so forth.
My aim is to ensure that my asset remains flexible enough for users to define and utilize their custom data types visually. However, the complexity lies in these data being of a custom type, not simply float, char, int, or string.
Given this context, any ideas?
parsing
you're describing a super broad problem
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yo ! I have a function that allow me to activate and deactivate the weapon hitBox at a certain % of the animation. If I press attack while attacking, my player will change the attack animation. I want first animation to crossfade to the next one. The problem is, if I use crossfade the animation normalizedTime isn't really the one of the next animationAttack, but a mix of the previous and the next. This prevent me from actually knowing if i'm at 50% of the animation for example. What should I do to be able to crossfade while still having my function hitBox working ? PS : If I use Play instead of CrossFade it works perfectly fine, in case your'e wondering
https://gdl.space/emawiboqey.cs
Hello, I have a question, about my Unity WebGL Build project. Where I'm making a C# Script call javascript functions. Before i ask, i guess my main problem would be I don't have a deep understanding of Javascript or C#, but I'm trying. I made a Javascript plugin, put it in my asset folder, and created a C# Script that calls a function from the .jslib file. This script runs fine on the browser after i build the project, however, im kind of puzzled as to why I get this error ```EntryPointNotFoundException: GetUserAgent assembly:<unknown assembly> type:<unknown type> member:(null)
DeviceInfo.Start () (at Assets/Script/DeviceInfo.cs:20)
When I test my build, this function gives me an issue
probably... but i'm looking for a general answer too...
Does anyone know if this dialogue system supports event based dialogue, like you can make a script or something do something after a dialogue choice has been selected: https://github.com/merpheus-dev/NodeBasedDialogueSystem
Or does anyone know of some branching dialogue system like that
If you didn't see my message :
Hi I am working on a pick up and drop object script and I wanted to make it so if I fling the camera before dropping it, it throws the object with the force applied to it but I'm having some problems trying to do that.
I tried it this way:
Vector3 desiredPosition = holdArea.position + holdArea.TransformDirection(objectOffset);
Vector3 moveDirection = (desiredPosition - heldObj.transform.position);
heldObjRB.velocity = moveDirection * pickupForce * Time.fixedDeltaTime;
and objectOffset is defined like this:
objectOffset = holdArea.InverseTransformDirection(pickObj.transform.position - holdArea.position);
and it wasn't the best solution because it just keeps getting close to my face if I run, what could I do to make it stay more in place on the holdArea?
nvm i found my mistake
does anyone know how can i populate an objects array automatically, like without having to drag and drop my objects in the inspector multiple times? i wanna automate it because im working with too many objects and i have to repeat the process for different scenes with different objects..
depends what you're trying to fill
also why not use prefabs, anything you do in one scene should affect all other prefabs
oh yea sorry i meant prefabs list
like a list of prefabs ?
if its a common shared list, put them in a scriptable object, you can have all other objects refer that list
mhm ill see thanks
why are my collisions not working? sorry for the sound btw, don't know where it comes from
looks like your animation / is moving it into the wall
or your Movement script
make the rigidbody dynamic and use velocity / addforce to move instead
does collision still work normally on kinematic?
afaik you have to do your own collision checks
maybe try dynamic with gravity scale 0 if you want physics
it pushes other bodies but will phase thru walls
if I set it dynamic collisions work but the player falls slowly
you can set gravity scale on a dynamic rigid body i think
if you script is overriding velocity that will also override gravity
you can only set velocity on your X in your movement
oh yeah, putting gravity on 0 and everything works perfectly, tysm
you don't want gravity ?
nope, it's like a pokemon for example
oh ok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
// w s a d
private bool [] inputsHolder = { false, false, false, false};
[SerializeField] private float moveSpeed = 2f;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
rb.velocity = Vector2.zero;
if (Input.GetKey("w")) inputsHolder[0] = true;
if (Input.GetKey("s")) inputsHolder[1] = true;
if (Input.GetKey("a")) inputsHolder[2] = true;
if (Input.GetKey("d")) inputsHolder[3] = true;
if (inputsHolder[0] == true) rb.velocity = new Vector2(0f, moveSpeed);
if (inputsHolder[1] == true) rb.velocity = new Vector2(0f, rb.velocity.x - moveSpeed);
if (inputsHolder[2] == true) rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if (inputsHolder[3] == true) rb.velocity = new Vector2(rb.velocity.x + moveSpeed, rb.velocity.y);
UpdateAnimation();
FillWithFalse(inputsHolder);
}
}
Does it seem like a good code for movement or you can find some good changes for it?
yes..
because I don't feel like writing always new Vector2 is a good thing, but I'm not sure you can change it because I'm new to c#
many changes needed
im sure there are tutorials online that have better code
for wasd I would just do
Vector2 input;
input.x = Input.GetAxis("Horizontal")
input.y = Input.GetAxis("Vertical")
You dont need input holder here, you might as well just set on the previous check. Also if its gonna be top down like pokemon maybe its just easier to use translation based movement? Can be more finite/discrete that way
navarone, can you look at this please ?
yeah I tried it but when I keep pressing w and then d at the same time it doesn't go right
yeah but I want it to move in diagonal too, with pokemon I meant the fact that it has no gravity but it is a bit different actually
not sure about animations
hey quick question how can i put a lerp in a function and then call that function whenever to do the lerp?
what part are you struggling with? seems like you know what you want
well no not exactly im a bit confused because when i put it in a function it only does it once but when its in update it works fine?
does it need to be in a IEnumator?
this is the code
when i put this lerp thats in update into the UpLerp Fucntion it dosent work
Because you're calling it in Start not in Update. Update calls every frame, Start only when the script is starting π½
ohhhhh
thank you
I am getting spanked by this next step. is anyone familiar with Emscripten? Ive go through 10-12 hours of reading regarding my issue, and this error seems to be abit trivial to diagnose π¦
ok i have a new problem, i have called one lerp but i want to then call another in a different function and it seems to not wait till the Coroutine is done to do the next one any ideas?
what exact behaviour are you going for
oh, you may need to yield till the next frame if you're just falling out the the scope
https://docs.unity3d.com/Manual/Coroutines.html
some info on the return types
oh, but the resource up there basically tells you how to exactly write for it with lerp
don't mind about the music, why is the background so blurry?
not blurry, I meant glitchy
in short, it's because the camera movement is not pixel perfect
For this section option. Is the Scriptable Object class the Visual Scripting Scene variables, a component (like Variables Component), or a normal C# class but instead of MonoBehavior it is Scriptable Object?
Sorry for the age old reply. got distracted with work through the past days
It is not a kind of component.
and how to fix it
ScriptableObject is kind of a unity object. You can serialize instances if them as assets and reference them front elsewhere
Iβm not very familiar with Visual Scripting, so I canβt say if itβs similar to something from that system
I personally wasn't finding an object called ScriptableObject in the menu, which was why I was confused.
Also my intention is for this ShipData database, is for the game to spawn it in depending on the user selected ship, so the data will change depending on what the player selected. PlayerLoadout handles what to spawn. ShipData is stuff like maxVelocity, turnRate, etc on the specific ship.
Since this is an object I assume it should work fine
Fen, can you take a look at this please ?
You won't find "Scriptable Object" in the Create Asset Menu. You need to define your own kinds of scriptable objects
It's much like how you derive from MonoBehaviour to create your own kinds of components.
that I can't really help with as I'm not an expert on the issue, I just know enough to recognize it π
my impression is that there are many ways to solve it, but it depends quite a bit on the game, engine and setup. hopefully someone else here knows more, if googling pixel perfect camera does not yield any results.
I know unity has this component, but I honestly have no idea if it's related to your problem, sorry.
https://docs.unity3d.com/Packages/com.unity.2d.pixel-perfect@1.0/manual/index.html
I'm not very familiar with how the animator works when you're manually cross-fading like that (or when you're in the middle of any transition, really).
Animation events might be a more reliable way to do this.
now I got it. Had to watch a fundamentals video for it. This looks just like what I needed. thx!
Yeah I heard about animation events. I'm gonna research about this then, thanks !
You might need to filter the events based on the weight of the animation state. Otherwise, the fading-out attack might fire whilst it's almost completely faded out.
You can receive an AnimationEvent in an animation event handler, and it has some info on it https://docs.unity3d.com/ScriptReference/AnimationEvent.html
including animationState and animatorStateINfo
Ok thanks, I guess it's the right way to go
how do i detect if my mouse pointer is hovering over a CERTAIN ui element?
I don't even need it anymore but tysm for trying to help me, I'll do a static camera game, tysm again β€οΈ
you can implement IPointerEnterHandler on a component you attach to the same object as the UI element you're interested in
OnPointerEnter will get called on it.
You can also use EventTrigger component to do this entirely in the inspector
it lets you add callbacks for each kind of event
what if the certain element can have multiple varients based on wether its on a different UI element will it still work then?
ok let me break down what im tryna do
im trying to make it so when you hover over a Level select it changes to show that level on the main worldspace, i ve got everything except the ui hover detection
Put it on whatever the graphic is attached to
there's a few input calls you can do depending if you're using the new input system or not
actually I dont think that matters anymore? Maybe they both work
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
That one in legacy but I know it still works
there's one other call I know because I know I ran into issues with this using it with the callbackcontext of the new (not really new anymore) input system
public class CanvasRaycaster : MonoBehaviour
{
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;
void Start()
{
m_Raycaster = GetComponent<GraphicRaycaster>();
m_EventSystem = GetComponent<EventSystem>();
}
public bool IsPointerOverCanvas()
{
m_PointerEventData = new PointerEventData(m_EventSystem);
m_PointerEventData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
m_Raycaster.Raycast(m_PointerEventData, results);
if (results.Count > 0)
{
return true;
}
return false;
}
}```
Ah, there's this way too I probably grabbed from the forums, but it's just a cleaner way to do this than above.
Im trying to instantiate a ramp object, it works, but I need it to instantiate in the length of a float called chunkLength, any ideas?
'public float chunkLength = 90;'
' GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");
foreach (GameObject position in rampEMPTY)
{
Instantiate(ramp, position.transform);
} '
#π»βcode-beginner message
same question, new variable names?
is the problem that it's not spawning at the correct location, or do you want to change the scale of the object you spawned to 'cover' chunkLength?
Wdym by "in the range of the float"?
im instintiating ramp objects into empty game objects with the tag rampTag, it works, the chunks with these empty objects have this script that Instantiates these ramps, but since multiple spawn, they duplicate into past chunks
i need it to only generate in a certain range to prevent this
if (Vector3.Distance(referencePoint, thingToSpawm) < range )
?
Still don't really understand though
like
foreach (GameObject position in rampEMPTY)
{
if (Vector3.Distance(position, ramp) < chunkLength)
{
Instantiate(ramp, position.transform);
}
}
?
that doesnt work
full thing
GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");
foreach (GameObject position in rampEMPTY)
{
if (Vector3.Distance(position, ramp) < chunkLength)
{
Instantiate(ramp, position.transform);
}
}
doesn't work
That is always a useless thing to say.
What doesn't work?
You are using position in the distance check
And position.transform in the instantiate?
What is position
GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");
foreach (GameObject position in rampEMPTY)
{
if (Vector3.Distance(position, ramp) < chunkLength)
{
Instantiate(ramp, position.transform);
}
}```
looks like `ramp` is your prefab? so you can't really `Vector3.Distance` on that
Sorry
I'm meaning there is errors, that's why it won't work
yes ramp is my prefab
Share the errors then.π€·ββοΈ
What is position?
Then you can't use it there
Argument 1: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'
Argument 2: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah. You can't use a gameobject in distance
You use a position
Well, two positions of course
This is what ive got
I should have posted it like this first anyways
no one can understand little code bits without context
That didn't need a link. Too short to be worth it
If you use a link, why not post the whole file?