#archived-code-general
1 messages · Page 92 of 1
Hi everyone,
I'm trying to setup my Unity project. I'm using VS code as external tools. My project has a multi-root setup. I saved a [project-name].code-workspace in the root directory of the project path. Now in the editor external tools arguments, I'm using "$(ProjectPath)/[project-name].code-workspace" -g "$(File)":$(Line):$(Column).
This works as expected when opening the project from unity : workspace is loaded, file script and line number are opening as well as it should.
Still this arguments in the external tools editor window is common for all the Unity project which use the same editor version, so it is fine only if I'm working on the correct project.
Do you know if there is an argument (like the $ProjectPath) which defines the project name ? Or anything like this I could use ?
Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5.
does anyone know how to use MeshCollider with kinematic Rigidbody (because I AddForce to it) ?
You need to use a convex mesh collider
If its not accurate enough to your shape, you can use multiple convex colliders, or preferably multiple primitive colliders (box, sphere, capsule) to approximate the shape
what's convex mesh collider?
Change the Convex toggle in your MeshCollider settings and see the difference
If its still unclear, google convex vs. concave
I have, fixed it, thank you
if(rb.velocity.x > maxspeed
{
float clampedx = Mathf.Clamp(rb.velocity.x, maxspeed);
rb.velocity = new Vector2(clampedx, rb.velocity.y);
}
sorry if it has already been solved
oh it has been solved more elegantly, nice
I'm trying to make the code generates only 2 obstacles, why is it generate 3??
Yep
Do you able to figure it out yet?
you just confirmed that you have 3 spawners
You've got three child objects, so you get three spawns
Yes I know but the thing is that, I want to make a system that if they generate 3 or them, one of them must be destroyed to prevent full road blocking
I want it to generate only maximum of 2
And left one of them empty
Well I want to make an endless runner game
Hmm, good idea
Hey, I have an inventory which has slots, and i have a hotbar (which is a different gameobject) which has 5 slots. I want to do a drag & drop system, like dragging an item frm the inventory to the hotbar. I tried to use the interfaces for that, but in my hotbar, i have the interface "IDropHandler", so the method OnDrop as well, but the variable "pointerEventData.pointerDrag" returns me the slot on the inventory where the item was before dragging... someone has an idea for that?
I just missed an information, it should fix the pb, thanks anyway ^^'
int Genrated; isn't a static variable, so it's independent for each script instance. It means that one script can have a different value than the other one. In other words, incrementing it in one script won't affect the other scripts.
Oh wait, I think I misunderstood the scenario. 🤔
oh
Well, when I'm looking at this code, it shouldn't spawn more than 2 objects, unless there are several instances of this script on the scene.
Yep, it shouldn't be
This is an Editor question;
How do I detect if there is mouse input in a specific Editor Window? For instance the Timeline editor window
I suggest #↕️┃editor-extensions
oh my bad
I've got a ball that follows the mouse on every Update().
debugBallPos = debugBall.position;
debugBall.position = Vector3.Lerp(debugBallPos, mousePos, 0.1f);
debugBallPos is a vector 2 version of the debugBall's position.
Line 2 just lerps it to the position of the mouse.
My question is, how do I constrain it to not go farther than a limit from the skeleton's torso
Acquire the distance between mouse and skeleton and set the target constraint of Lerp to skeleton position + mouse direction * Mathf.Min(distance, max).
Note: this would produce a circular max distance constraint.
how do i fix this
Note: this would produce a circular max distance constraint
thats what im going for
Code editor configured yet?
By showing more context
put a , before transform.rotation
alr
ok it fixed it but now i got another error
i dont know how i pressed the link you sent
Stop. Configure your Editor and post questions properly #854851968446365696
You read the page that opens and apply the steps in it
im blind or someting beacuse i cant find any windows < package manager
yes i know bro
Distance between mouse and the ball?
i finally found it
The function has been given to you prior to this already in beginner code where there was a miscommunication about the type - it's not int or string.
I know how to find the distance
but why mouse and ball?
everyting is the latest version now
the ball is alr getting lerped to the mouse
can you help now?
Post a screenshot of your code editor and we'll see if it's set up now
this?
Yeah, it's still not set up properly
wait i can show i got everyting
If you haven't done that already, restart it
alr
Also the guide isn't just about updating everything, there are more steps, go through it all
Meant skeleton and mouse
alr i restarted the app
what now
Ok gocha
Your errors will be underlined red in the code
it aint any text thats red underlined tho
If that's not the case, then pick up the guide where you left off and finish it
alr
ok i did edit < preferences and then i pressed on external script editor and this was the only one that showed up is this the right one?
Well you should be able to determine that yourself, since you have control on what you install on your computer
But yes, that's the right thing to select
Yes that won't solve your error
then what will
It's meant to give you a better programming experience
oh
wait
it is a red underline now
i fixed it
letss gooooooo
See? The underline did it all, I didn't even need to tell you where the error was or what to do
How do I make this visible in the inspector
You can't, the setter must not be private or protected
found the solution - field: SerializeField
^ yup, need to specify the backing field of the auto property in order to serialise it
The attribute not erroring when put on a property is plain stupid
Ah, Unity, Peak development experience
Pretty much. Unity needs to suggest the field variant
debugBall.position = Vector3.Lerp(debugBallPos, torso.position + mousePos * Mathf.Min(Vector3.Distance(torso.position, mousePos), flingLimit), 0.1f);
is this it?
Mouse direction
?
direction would be equaled to mouse position minus skeleton position (screen space), normalized
aha
Nah they just need to add one line: [AttributeUsage(AttributeTargets.Field)] and the compiler does the rest. It'll error if not on a field
so smth like this
debugBall.position = Vector3.Lerp(debugBallPos, torso.position + (torso.position - mousePos).normalized * Mathf.Min(Vector3.Distance(torso.position, mousePos), flingLimit), 0.1f);
?
a direction from A to B is always B - A
var distance = ...
var direction = ...
debugBall.position = Vector3.MoveTowards(debugBall.position, debugBall.position + direction * Mathf.Min(distance, max), speed);```something of the sort.. (coded from mobile discord - possible errors)
debugBall.position = Vector3.Lerp(debugBallPos, torso.position + (mousePos - torso.position).normalized * Mathf.Min(Vector3.Distance(torso.position, mousePos), flingLimit), 0.1f);```
this is what I have
Its close
but it doesn't limit the distance
it just reduces it
Lerp's probably not what you'd want to use
move towards?
Aye
That's just how fast you'd want the ball to go towards your mouse - maximum speed
Try some values
How are you acquiring mouse position?
it doesnt hard limit the circle
Input.MousePosition
Show what you've got.
then I convert it to world position
That would be screen space. Alright
mousePos = Input.mousePosition;
mousePos.z = 10;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
yea
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yes
im not
Set the z position after converting to world space
Now it just follows the mouse
spot on
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = 0;
Congratulations
What is fling limit?
Its meant to be the distance
but I havent implemented it
into anything yet
which i probably should lol
That would be the maximum distance the ball would be from the skeleton
yes
Everything else was for moving the ball towards the mouse. Seems like you've got it, good job.
Now my only problem is that the skeleton sometimes jumps much farther than usual
lemme try send a clip
This happens even though the Fling values are normal
fling Velocity
why am I getting this error in a completely new unity scene? I've not added anything and yet I get this error? I'm using unity 2021.3.24
Version control package, update or remove it. Theres a bug with it
Lots of people had that issue
uuuh, sorry if I'm not understandingt correctly, update what exactly? Should I not use this unity version?
The package for version control is currently bugged. Your unity version is fine
Search for version control in your package manager
right, I see it, thank you very much!
I have an attack (the big white rectangle) which is instantiated when the player attacks and then deleted a bit later
and I want it to do stuff when colliding with objects with the tags "enemy" or "bouncable"
but it's not working?
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("attack collided with " + collision.gameObject.name);
if (collision.gameObject.tag == "enemy" || collision.gameObject.tag == "bouncable")
{
Debug.Log("bounce");
}
}
neither of the debug logs are triggering
the script is on the gameobject of the attack
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
Do you have all the specifics that the docs say to do?
Oops that's 3d, updated link
No rigidbody?
it needs a rigidbody? 💀
i thought it just needed a collider
Yup. Or at least the 3D one does.
Hey everyone, how do I make raycast2d stop from giving me a bunch of errors when it hits nothing
Raycast hitting nothing isn't a problem in of itself, but if your code is trying to do stuff like "getComponent" on nothingness, then yeah it will freak out.
You probably just need a null check. Dunno if there's some other way.
how do i make a null check
You just put in an if statement that check that the thing you hit isn't null.
if (thingyYouHit != null){do stuff}
That way it won't do anything when it hits nothingness (returns null)
For collision to happen, 2D or 3D, at least one of the colliding objects do also need a rigidbody, since your using 2D colliders, you should also use a 2D rigidbody on whichever object youd (by default) want to be affected by gravity, and physics, though the gravity part is optional
because you are doing it in Update()
never do physics stuff in Update()
Everything else is done in Update
move the rb.velocity stuff in FixedUpdate() and change Time.deltaTime to Time.fixedDeltaTime
but I think I've already found a fix
maybe
yes, so move the physics stuff out of it
Ok ill try your stuff
Input still should be in Update
use a container value to check when you press a button in update
check that container value in the if statement and reset it back to false at the end of the fixed update
bool mousePress = false;
void Update()
{
...
mousePress = mousePress || Input.GetMouseDown(0); //fix by @Sidia
}
void FixedUpdate()
{
...
if(mousePress && !onCD)
//change velocity
...
mousePress = false;
}
also why not just use rb.AddForce(force, ForceMode.Impulse)?
I didn't know that was a thing 💀
well now you do :)
If 2 Updates happed before fixedupdate you might miss a mouse click with this
thx
except you don't
read the code again
2nd Update will set mouseDown to false before fixedupdate
or do you mean that only the last Update will work?
Is possible to create a class that have another class in it?
For exemple i have a item class that have (name, image, etc)
And i want to create another class, for exemple weapon, that is inside of item class or that have the the item class atributes
Use mouseDown = mouseDown || Input.GetMouseDown() then it wont reset
yea that's a good fix
thank you, it works now
wouldn't that actually make the mouseDown be true always?
Not if you set it to false in FixedUpdate
true true
try it
Try my fix above
The problem is especially happening if you have a very high frame rate
yes true
Or just do it in Update
Adding a single impulse force in update is fine
It will take place when the next FixedUpdate/physics step happens
Continuous forces though, those you need to do in FixedUpdate
just make sure to use Time.fixedDeltaTime
or else you'll have way too different forces applied every time
damn those lines too stupid so unity refuse to run it xd
unity editor when press play will not responsible xd
any better idea guys?
It is possible, though for the case you described, I think it would be better to treat your item class as just data, in a serialized class, then create an instance of it in your weapons, armor, potions, etc classes, either as a public or [SerializeField] to set it through the inspector (serialized field is a more cleaner approach), since it sounds like your weapons etc will want to use or depend on data set from your item, another approach could be inheriting from your item class (or using interfaces), if every item like weapons, potions etc may share functionality too
you have an infinite loop on line 127
your condition is checking j < something but the incrementor is incrementing a different variable called i
i is not j
oops
im baka
second time i did it
It's an understandable and common mistake to make, 😉
XD
Are you sure?
.velocity and AddForce as an impulse shouldn’t be affected by fps
My problem was fixed by removing deltatime
oh damn crashed
show new script
you put j++ on line 127 ?
yes
What will this do?
no crash
gud
Thank you! This is always a concept I've been scared to try, but music is my favorite part of most games, so I'm super stoked to actually face the challenge haha
I am having a problem:
I have a item class and a Equipment class that have the item class as inheritance
In my Gameobject i have a item reference that i can place my equipment item
And i want to use for exemple a function that uses the Equipment item -> useItem(Item item)
The problem here is that i cannot use the Equipment class features
How do i turn around on this?
I cannot create a Equipment reference on my game object because other types of items will be in that reference too
why am i getting a error here?
i know i have to define it in a certain way, however i cant find any information about it
I saw this post, but I believe they changed it because it isnt working for me
Can I assign a method to a unity event in script?
I didn't use them like that so far, it's just a handy way to refer to a method in my buttons through editor.
Right now I want to change one of my button's event from one method to another. So RemoveAllListeners, and then add the new one?
you cannot remove listeners assigned in the editor
Ok, thanks for the info, I'll work around it then.
you can change the ListenerState so they do not exeute, that might help
public class P_Controller : MonoBehaviour
{
[SerializeField] private InputAction Boost;
private void Awake()
{
Boost = new InputAction("Boost", InputActionType.Button);
Boost.AddBinding("<Keyboard>/a");
}
public InputAction GetBoost()
{
return Boost;
}
}```
```cs
public class P_Movement : MonoBehaviour
{
[SerializeField] float RotSpeed;
[SerializeField] float RotBoost;
float OGspeed;
P_Controller controller;
private void Awake()
{
controller = GetComponent<P_Controller>();
}
void Start()
{
OGspeed = RotSpeed;
}
void Update()
{
Boosting();
}
void Boosting()
{
if (controller.GetBoost().ReadValue<float>() > 0)
{
OGspeed = RotBoost;
Debug.Log("bossted");
}
else
{
OGspeed = RotSpeed;
}
}
}
Hi sorry, why didnt this work? 😦
when i Press A, nothing happen?
if properties are just methods why cant you
int prop {get;set;}
void Foo()
{
prop;
}
Isn't that just a statement without an expression? I don't think you could plop down a method name there either... I'm not quite sure what you're asking
asking for invokation
I don't think properties are methods, maybe you could consider their getters and setters properties
so assume there is a lazily initialized property, you cant just invoke it to force init
and if you do cs var a = prop;
As soon as you add () it becomes an invocation, which you can only do on functions or variables of type func or action
there is no guarantee it wont be stripped by compiler
ah I see
its complicated
I'm sure it is
Might be worth moving it over to a class and controlling it's initialization with an initialize function
(e.g. start a task in the constructor and then whenever you need that instance check if the task is completed)
But generally if you are doing these weird thjngs than that should be a trigger that your architecture doesn't support the flow that you want
ok
THANK YOU
whats the proper way to lock transformations in editor apart from ExecuteAlways/Update
I'm trying to implement a system where when you open a door, you roll a dice and that determines what "room" is spawned. But for some reason, when I instantiate the room, the first one places PERFECTLY, but afterwards they all spawn on top of each other regardless of my offset method. I have a feeling it has something to do with the Room Properties Scriptable Object but I'm not quite sure
If someone could give a quick peek it would be much appreciated!
line 54
no assigning
ah, I got it now, thank you!
How do 2D Top down isometric games allow players to interact with the tilegrid in a systemic way? For example if I have a tree, I want my character to be able to cut it
use a gameobject that is intractable
or make the tile a scriptable tile
Would I make every interactable tile a game object?
And would that still work in a tilemap? Also how does layers work in this case, what if my sword chops down foliage, but my shovel digs a hole
hi, I'm trying to make a string that gives me the name of the current animation of the player in a game, this is what I have:
string currentAnimation()
{
string anim;
anim = gameObject.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).shortNameHash.ToString();
return anim;
}
But I'm getting this: error CS1503: Argument 1: cannot convert from 'method group' to 'object'
probably the error comes from elsewhere
share code and what error, which line and which script
this ain't it
ok I found it, I didn't put () when I called the function using Debug.Log
shouldn't I get the names of the animations instead of numbers?
like these names
you're getting the hash of the name not the actual name
is it possible to turn it into the name?
theres a method that converts hash to nae
Is there? i know there's StringToHash but I don't see a method for the reverse
not sure you even can
why would you need that? if you're using strings to play animations you should probably hash them and use those instead
yep
pulled straight out of my bottom
lol
i put ToString because I thought it would give me the name of the animation
i'll try using the number
that doesn't answer the question i asked
GetCurrentAnimatorStateInfo(0).IsName can be used to check if it's in a certain state name but that's about it
if only hashtables existed
if you need to do things based on state just use the FSM scripting in animator
imagine the magic of having couple kbs more memfoot but being able to loop up things
Animancer all the way
just because it's easier to notice which animation it is when I read the code
that crashed unity
doing that itself wouldn't cause any errors. you probably have an infinite loop
i think so
I've used this countless times no crash..it's something else.
how do I stop the simulation if I can't open the editor
kill the process
if you have infinite loop. Alt + f4
It's because I did an infinite loop
or wait till your memory gets all eaten up and crash xD
int numOfColliders = Physics.OverlapSphereNonAlloc(transform.position, explosionRadius, explosionHits);
for (int i = 0; i < numOfColliders; i++)
{
IDamageable damagable = explosionHits[i].GetComponentInParent<IDamageable>();
if (damagable == null || !hitSkeletons.Add(damagable)) continue;
damagable.TakeDamage(damage);
}```
is there an alternitive to this? I don't like pre assigning an array to 64 etc, esp what if the colliders filled do not contain the component I want (imagine theres like 50 `IDamageable`) within the overlap area, but only 10 get picked up coz of other colliders, that's quite bad
is there an alternitive? (increasing the allocated array size is not an option)
layermask to prevent extraneous colliders from being included
oh shit, I didnt even know
Why does OnCollisionEnter2D not work?
void OnCollisionEnter2D(Collision2D other)
{
Debug.Log("COLLISION");
if (other.gameObject.tag == "BoxesTag")
{
box.enabled = true;
}
}
also keep in mind that Rigidbody2D is not a collider itself, you will also need a collider on that object (or one of its child objects)
oh
Right
I have to check those colliders too
hm
IDK
Nothing seems off on those colliders
then click the link and go through those steps
I'm trying to build my game, but the touch input breaks when it's built, and i don't know why. The touch of my script only works on Unity Remote, but not the editor nor build app. Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DrawingScript : MonoBehaviour
{
public float inkMax = 100f;
public float inkCurrent;
public float inkBeforeCalc;
public int maxDrawings = 2;
public float drawOffset;
public GameObject linePrefab;
public Tilemap tilemap;
private LineRenderer[] lineRenderers;
private EdgeCollider2D[] lineColliders;
private int currentDrawing = 0;
private Vector3[] linePositions;
private bool isDrawing = false;
void Start()
{
// initialize the array of line renderers
lineRenderers = new LineRenderer[maxDrawings];
lineColliders = new EdgeCollider2D[maxDrawings];
for (int i = 0; i < maxDrawings; i++)
{
GameObject lineObject = Instantiate(linePrefab);
lineRenderers[i] = lineObject.GetComponent<LineRenderer>();
lineRenderers[i].positionCount = 0;
lineColliders[i] = lineObject.GetComponent<EdgeCollider2D>();
}
linePositions = new Vector3[0];
}```
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
if (inkCurrent <= 0)
{
inkCurrent = 0;
inkBeforeCalc = 0;
isDrawing = false;
return;
}
// start drawing a new line
isDrawing = true;
linePositions = new Vector3[0];
}
else if (touch.phase == TouchPhase.Moved && isDrawing)
{
if (inkCurrent <= 0)
{
inkCurrent = 0;
inkBeforeCalc = 0;
isDrawing = false;
return;
}
// check if the touch is over a non-colliding tile
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(touch.position);
Vector3Int cellPosition = tilemap.WorldToCell(worldPoint);
TileBase tile = tilemap.GetTile(cellPosition);
if (tile != null && !TileIntersectsCollider(worldPoint))
{
// add to the current line
Array.Resize(ref linePositions, linePositions.Length + 1);
linePositions[linePositions.Length - 1] = Camera.main.ScreenToWorldPoint(touch.position + new Vector2(0, 0));
linePositions[linePositions.Length - 1] = new Vector3(linePositions[linePositions.Length - 1].x, linePositions[linePositions.Length - 1].y, drawOffset);
lineRenderers[currentDrawing].positionCount = linePositions.Length;
lineColliders[currentDrawing].points = linePositions.toVector2();
lineRenderers[currentDrawing].SetPositions(linePositions);```
inkCurrent = inkBeforeCalc - calculateLineLength(linePositions);
}
}
else if (touch.phase == TouchPhase.Ended && isDrawing)
{
// finish drawing the current line
isDrawing = false;
currentDrawing = (currentDrawing + 1) % maxDrawings;
inkBeforeCalc -= calculateLineLength(linePositions);
inkCurrent = inkBeforeCalc;
if (inkCurrent <= 0)
{
inkCurrent = 0;
inkBeforeCalc = 0;
isDrawing = false;
return;
}
}
}
}
float calculateLineLength(Vector3[] linePositions)
{
float lineLength = 0f;
for (int i = 0; i < linePositions.Length - 1; i++)
{
lineLength += Vector3.Distance(linePositions[i], linePositions[i + 1]);
}
return lineLength;
}
// helper method to check if a point in world space intersects with the collider of the Tilemap
bool TileIntersectsCollider(Vector3 worldPoint)
{
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
return hit.collider != null && hit.collider.GetComponent<TilemapCollider2D>() != null;
}
}
public static class V3Extention
{
public static Vector2[] toVector2(this Vector3[] v3)
{
return System.Array.ConvertAll<Vector3, Vector2>(v3, getV3fromV2);
}
public static Vector2 getV3fromV2(Vector3 v3)
{
return new Vector2(v3.x, v3.y);
}
}```
please use a bin site to paste large blocks of !code 👇
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I am having a problem:
I have a item class and a Equipment class that have the item class as inheritance
In my Gameobject i have a item reference that i can place my equipment item
And i want to use for exemple a function that uses the Equipment item -> useItem(Item item)
The problem here is that i cannot use the Equipment class features
How do i turn around on this?
I cannot create a Equipment reference on my game object because other types of items will be in that reference too
show full script
public class CollisionHandler : MonoBehaviour
{
public BoxCollider2D collider;
// Start is called before the first frame update
void Start()
{
collider = gameObject.GetComponent<BoxCollider2D>();
}
void OnTriggerEnter2D(Collider2D other)
{
switch (other.gameObject.tag)
{
case "BoxesTag":
{
collider.SendMessageUpwards("GetBox");
break;
}
}
}
}
still nothing working
What its colliding with
you have a rigidbody2d on one of those objects, right? and they are on layers that can collide?
you're looking at the physics 2d settings, not the physics settings?
Yea
okay and you have a rigidbody2d on one of the two objects, right?
There's no Rigidbody
I added a rigidbody to that collider
this is the collider attached to thhe player
And this is for the other one
your rigidbody is static. two static colliders do not produce a collision/trigger message
But doesnt that need 2 rigidbodies?
you need at least one non static rigidbody to produce a trigger message
Do you guys know where I should go for a sprite issue? is that in graphics? Or can I get some help here?
Is it blurry
Ohhhhh
thx
read the page i linked next time
It looks like one the sprites just bugged and became this pink color
I also had to tick this
like a purple and pink type
that doesn't matter. the rigidbody is static
I have 0 clue as to what can solve this:
I don't even know what happened to one of the sprites for it to just turn pink
this is for sure not the right channel for this. but it looks like what happens when you deleted a sprite asset without first removing it from the tilemap/tile palette
mmmm I did perhaps do that a minute ago. How can I solve this?
also where's the right channel then
#🔎┃find-a-channel check here for a list of all channels and their purpose
can unity detect collisions if im manually updating the positions?
i have one object manually moving left (position -=1) and another moving right (position +=1), will the oncollisionenter function detect the collision?
right now my code for whatever reason isnt detecting collisions and im not sure if its because im manually moving objects or something else
MovePosition might work.
Transform.position does not
Or if it does, it is pure chance
you need a rigidbody on at least one of the objects for collision messages to work
and if you have a rigidbody you may as well move using that instead of teleporting it via the transform
Yeah, sounds like you might as well use rigidbody.velocity to move them at a constant speed
Is there a difference between loading the scene the first and the second time?
what happens?
i'm gonna guess you have a DDOL object that loses references because you change/reload the scene
When i load it aigan a object is not existant anymore which executes crucial code
a singleton?
off to google whats a singleton
could also show relevant code and errors
Should be a singleton
so are you expecting us to magically know your code to provide an answer or do you want to maybe share relevant code and errors so i can helpfully point out for a second time that when you reload a scene the DDOL object won't keep the same references to non-DDOL objects because they are different objects
if it is a singleton most likely you are not properly cleaning up the static field
as a result the gameobject is destroyed but the wrapper is left in the field and doesnt equate to null
but yeah, all that is just fart in the wind until you show the code
if(isPlayer)
{
NetworkClient.Disconnect();
string path = Application.persistentDataPath + "/saves/soul.book";
File.Delete(path);
Debug.Log(path);
if(isServer)
{
NetworkServer.Shutdown();
}
SceneManager.UnloadScene("Server");
SceneManager.LoadScene("CharacterCreationMenu", LoadSceneMode.Single);
}
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
this doesnt seem relevant to your issue
Thats why i am asking here Xd
please provide relevant errors and the code the error points to
preferably the entire class where the error happens
I am not getting an error, it is just a behavior of the code i cant explain my self so far
if you cannot even explain what the issue is then how do you expect anyone else to know what the issue is and how to fix it?
especially since you aren't even providing the full context
so do you have a singleton?
I think the object which dissapears is a singleton
hi,
is it possible to lerp through multiple colors at the same time to result something like a gradient rainbow color ?
i only know how to mix 2 colors together
Color.Lerp(color1, color2, ratio);
but houw about 6 ?
the expected results is to be like that
lerp in a loop where each color is an element of an array, when you reach the end of the current lerp progress to the next iteration of the loop until you've completed all colors
afaik blending colors in such manner is near impossible with simple tools like lerp
but i dont know for sure
but yeah, it probably won't look too great just lerping like that
hmm , I did try the loop solution before i asked and yea the end result is just blending of 2 colors.
so is theres any tool that can do it ?
sounds like you probably did something wrong if it just looked like blending just two colors
because in code its just numbers, which dont work nicely with human eye perception
You want to blend the HSV values.
could u show me how is it done?
that is a possiblity , a simple example would be appreciate it ,
i tried to write one myself here but discord is bugging for me
I think jaws proposed the best solution
Hue let's you get the full spectrum and pin point the exact color you want and when
I'll try it out
@hollow stone thanks a lot 🙂
@solemn raven Since you said this
i only know how to mix 2 colors together
I wanna point out that Gradients are a thing too and have a nice editor
https://docs.unity3d.com/ScriptReference/Gradient.html
You would just set it up in the inspector or via code, then sample it withGradient.Evaluate
But yes you want HSV for the rainbow
thanks , yes i tried gradient it gives u the color based on the time value , not a rainbow , i used the default example as well
i'll try the HSV
Well it gives you a rainbow if you set it up as a rainbow
It is nice to setup, but does not give correct values when it interpolates between colors if you want as said the hue changes.
Yep, as I said, for this particular effect using Hue is more robust
Just kinda sounded like he wasn't aware of gradients
I'm trying to use "Hinge Joint 2D" to make the arms for my character flop around while they move but they aren't affected by physics
do they have rigidbodies?
yeah
Are the constraints frozenm?
for the actual body yes but not for the arm
Any tips on preventing splash damage from going through walls ?
are the rigidbodies Dynamic rather than kinematic or static?
raycasting to check wether level geo is in the way yieds very poor results
both are dynamic
then sounds like you should move your question to #⚛️┃physics
I'm a bit confused. Shouldn't imports be handled automatically?
Trying to import the character class from my Entities folder
you're using an asmdef, you need to reference the assembly that the Character class is in
ah, ok I'm a bit out of my depth here
what's an asmdef?
How would I import the assembly that the character class I made is in?
Is it in a namespace? i can see a .cs file
oh even better, it looks like you're using an asmdef only for the Scripts folder for whatever reason. is this code you just yoinked from somewhere? is that why you somehow have an assembly definition that you don't know about?
I'm using https://github.com/endel/NativeWebSocket
the issue is what i posted above. they have an assembly definition only in the Scripts folder, do not have one that the Character class is in, and therefore cannot reference the correct assembly
and it told me to just post the files in Assets
why are you modifying it?
either way though, just delete the asmdef file and it should work just fine
I'm not, the WebSocketClient is my own class
then put all of the stuff that came with that package into its own folder so you aren't creating classes in its assembly
yes
The type or namespace name 'NativeWebSocket' could not be found (are you missing a using directive or an assembly reference?) [endel.nativewebsocket]csharp(CS0246)
i get this now when I try to import it into my custom client
click the asmdef file in unity and make sure it has the automatically referenced box selected
Wait can you import Javascript libs in Unity?
i'd imagine that's probably for the webgl support
Hey folks, using the XR Interaction Toolkit, is there a way to replace a grabbed object with a different one?
oh jk, it works, just needed to restart unity and omnisharp
Please ping me if you have an answer (:
still can't import character properly for some reason:
Inconsistent accessibility: field type 'Character' is less accessible than field 'WebSocketClient.character' [Assembly-CSharp]csharp(CS0052)```
ah, the Character class is also not public
oh nice, that fixed it, didn't realize I had to make it public, thanks
the error is complaining that the type of the field isn't going to be visible to everyone who has access to the field
I'm trying to make it so that the red rectangle will be clamped from 90 to -90 on the while looking at the mouse on the left side. However, the rectangle will only look to the right side. Switching the 90 and -90 only makes the rectangle look at 90 or -90. Does anyone know how I could solve this?
hi ,
i couldnt get it to work , could you help me setting it up correctly ?
Color BlendColors(Gradient gradient){
Color result = default;
float colorCount = (float)gradient.colorKeys.Length;
float hueSum = 0f;
foreach (GradientColorKey colorKey in gradient.colorKeys)
{
Color.RGBToHSV(colorKey.color, out float hue, out float saturation, out float value);
hueSum += hue;
}
float averageHue = hueSum / colorCount;
result = Color.HSVToRGB(averageHue, 1f, 1f);
return result;
}
is this how we suppose to do it ?
search this discord for "clamp camera" and you'll see plenty of examples of how to clamp rotations (once you get past the many messages of me suggesting others to search that)
also configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
What is your code here supposed to do exactly?
this probably isnt the best option but you could make a raycast to all objects with a tag/layer in the splash range and if it has a clear LOS than damage it
mix hue and then return the value to vertex.color
it doesnt make sense to me , i think i dropped the ball somewhere
anyone know how if theres an efficent way of making UI for any sort of counter(health, ammo, stamina) that essentialy displays the same ammount of sprites as the counter shows? example is i have 3 bulets so there is 3 bullet sprites at the bottom of my screen indicating the ammount of ammo i have. i shoot one and now there is only 2 bullets.
What is the input?
ther is a way where you can do it like ```if(bullets == 3)
{
bulletSprite3.setActive(true);
}
else {
bulletSprite3.setActive(false);
}//repeat for sprite 2 and 1
oh, im sorry, i forgot the first line Gradient gradient
But what are you blending by?
im looping throw a list of UIVertex which referes to the vertexs of an image and applying each vertex.color to the result of the function , that sounds odd to me , not sure if that is the right way to do it
Sorry but I still don't get it. First you ask how to "lerp through multiple colors", but the method you wrote does not take any lerping value? What determines what color of the gradient each vertex should have?
oh forget about what i said, i was trying to explain what i wanted , all i want is how do i create something like this and apply it on an image
i have very limited experience with shaders and colors in general , but i have heard that wt could blend multiple colors via code, if we somehome told the code on the far left for example to be blue and gradually change to pink after 20% of its width then red .... then finally yellow , that sounds like a plan i just dont know how to do it ,
i'd suggest lerping a hue value
and then using that to compute colors
consider Color.HSVToRGB
it converts a hue, saturation, and value to a Color
hue is the kind of color it is, saturation is how strong the color is, and value is how bright the color is
please show me a simple code, im lost when it comes to shaders and colors, even the simplest thing dizzles me.
Color.HSVToRGB(0f, 1f, 1f) will spit out red
oh, you're using RGBToHSV there?
lemme have a look
sure 🙂
this is just averaging a bunch of hues
averaging hues is not meaningful
just do something like this
yeah it gave me colors that was not on the gradient at all lol
some of which were too dark
float t = 0;
while (t < 1f) {
Color color = Color.HSVToRGB(t, 1f, 1f);
t += 0.05f;
}
this will compute 20 colors
Though, you dont want a value of 1
going through the usual random
As it will be white
HueSaturationValue
as in, lightness would give you white
oh, I'm familiar with..."HSB". thanks, Photoshop
ah, okay, I had it right there
the HSL model gives you white with a lightness of 1
yea you did it right
the HSV model gives you colors with a value of 1
i love color models
i kind of get L*a*b
L*a*b is pretty great for blending between colors, actually. I used it once to program my smart lights...
I see, youre right
i'd have absolutely tripped on that if it was HSLToRGB
Yep, you made me realize I've been thinking of value as "lightness" this whole time
i didn't actually think about it until now, lol
Didnt notice that you need to have 0 saturation to have a white output
especially because Photoshop talks about "HSB"
i think it's just HSV
probably
now let's talk about gamma curves and sRGB
🫠
Pls no
im trying to make sense of all that
btw @heady iris thx so much for sharing , im starting to actually get some results
float x;
while (t < xf){
ver.color = Color.HSVToRGB(t, 1f, 1f);
t += 0.05f; }
so i have included (x) in my forloop and gave x different values just to see different results
when x = 1 this is what i got
where is the blue ? 😄
nvm found it 0.75
yeah
HSL (for hue, saturation, lightness) and HSV (for hue, saturation, value; also known as HSB, for hue, saturation, brightness) are alternative representations of the RGB color model, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes. In these models, colors of ...
that's where I stole the figure from, lol
HSL is closer to how paints work
Any reason I shouldnt put rigidBody on the environment, instead of the player?
I've got Players, and Enemies - they don't need to collide, but both should collide with environment. So, I can have a RB on Player and Another on Enemy, -or- I could put 1 on the environment...
It needs to be on the moving objects
why would you want the environment to have physics?
Simply put
you COULD put a kinematic rigidbody on the environment, I guess
environment would be kinematic or static
You could, still need a rb on the characters though
but then you'd need a non-kinematic rigidbody on the player anyway
well making it static means you'd still need a rigidbody on your characters for collision messages
source link?
If the environment isn't moving around being affected by everything, then static or kinematic (in certain instances) are fine . . .
since static was an option for the RB it sounds like this is probably for 2d. so this may help clear things up: https://unity.huh.how/programming/physics-messages/3-collision-matrix-2d
Maybe for continuous collision detection you might wanna add a RB to some walls
static rigidbody counts as static in that matrix
correct, 2d
ooh, this is 2D
But meh
grid is basically identical though so it doesn't make much difference here. the resource i linked just has a slightly better explanation about the grid than the docs would provide
yeah
anyone ever connect a unity game to a local .net core process using websockets? I manged to get a discord bot doing something i wanted but i had to end up doing it in .net core after like 8 libraries failed to implement what it claimed to, and now i'm struggling to get that data to the game's runtime
i was thinking i could just run the .net core app as a process and monitor its output
I tried using nativewebsockets on the unity side to create a socket on 8080, and used websharp on the .net core app to connect to the socket on 8080 but the unity app hangs while creating the socket and the .net core app fails to connect
any ideas on how to get this working? I want to make a soft reference to "TriggerFunc" so I can call it across multiple different components iwthout having to name each one
i do not know what "soft reference" means
do you have a specific class that has a function called TriggerFunc?
sorry I'm new to unity
or do you have several unrelated classes that all have a function called TriggerFunc?
that is what I am hoping to achieve
you need to create an interface, then
mfw when I asked my friend if interfaces were in unity and they told me no:
well, interfaces aren't in "unity"
they're a C# thing
but I would agree that you can use interfaces when working in unity :p
how hard you think interfaces are to setup cause im in game jam and im debating just manually hard coding in each reference cause of time
literally trivial
very very easy
the methods you want as part of the contract, define them in the interface, inherit from the interface, and you're off to the races
indeed
you won't even have to change anything in the concrete classes
other than declaring that they implement the interface
then, you can use the interface type in place of that Component type in your code
an interface is literally just that, like the plug/socket combo's in your house are interfaces
as Stropheum said, it's a "contract"
you don't need to be an electrician but you can arbitrarily and modularly wire any electrical device into your home because you just rely on the interface
it's a promise that you can do X Y and Z
or, in this case, just a promise that you can do X
I'm a nublet and even I find interfaces relatively easy to use, shouldn't be a problem.
I came from UE5 so I knew what interfaces were, I just asked my friend if unity implemented them when we were setting up interaction system and he told me no so I just ran with it and now im like "ok surely there has to be an easier way thats at least similar" lmao
in this case, it would be like
public interface IWallSocket
{
public void PlugIn();
public void Unplug();
public void SetActive(bool isActive);
}
every language has interfaces and they're all pretty much the same
only thing is in unity (and i hate this) you can only serialize concrete types to the inspector
which is fucking annoying
[SerializeReference] correctly handles abstract classes
although you have to write your own property drawer
zoop
abstract classes but not interfaces
which is kind of pedantic but it fucks with the coding by contract paradigm
So you would write this on the class that would be calling the functions from the game objects ye?
no you would tell your class to implement it
public class DishWasher : IWallSocket
{
public void Plugin()
{
//do things a dishwasher does when you plug it in
}
public void Unplug()
{
//do unplug things
}
public void SetActive(bool isActive)
{
//turn the dishwasher on or off
}
}
so then you can have like a house electrical controller that does something to the effect of
public class HouseElectricalSystem : Monobehaviour
{
private List<IWallSocket> _homeAppliances;
public void OnPowerLoss()
{
_homeAppliances.ForEach(x => x.SetActive(false));
}
}
lmao
so the house electrical system doesnt give a shit if it's a dishwasher, a vibrator, a stove, your phone. all it cares is that it's something you plug in
javascript is an objectively bad language
if anyone disagrees, ask them where the triple equals sign came from
they had to add === because == didn't work 
Definitely not a fan of this. Had to get around creating a loot system with polymorphic classes . . .
i started watching a tutorial ontop of the explanations and I think I get it now although the only thing im confused about is creating the interactable do I just make a C# script or somethin and then change it to be that
yeah, if you create a new C# script in unity, it's pre-filled with some stuff
my workaround is usually like some kind of composable attribute system for like-things
throw that out and write an interface
and then i can make scriptable object instances for each configuration
i usually just create a new file from my code editor
good luck on your game jam btw
rule of thumb is get it done. if you catch yourself trying to be clever in a game jam your game is gonna suck
i've been burned multiple times getting inspired to make a really elegant system
so I do just make a C# script and chuck it all out ye?
and also I don't need to attach the interface like a component right I can just add it in the code to the script for the object in the class section ye?
correct: the interface is not a component
public interface IMyInterfaceThing
{
public void MyDeclaredMethod1();
public void MyDeclaredMethod2();
//and so on
}
convention is to previx interfaces as generally like I(Verb)
like ICompressable, or ILovable
those are adjectives
Yeah, I think you actually can't attach an interface to an object even if you try.
The interface does not physically exist within Unity. You just implement it from a class . . .
me being proud and making a text based system for dialogue despite it not being the wisest idea:
ima just try to finish then polish later when more time
Funnily enough first time using unity.
fourth game jam tho, first jam I did was first time using UE5, then second was a collab with a friend using their preferred engine (godot which I forgot how to use cause i didnt for a year or so) and third was solo UE5 again
this time im using unity cause I thought what the hell yknow might as well learn somethin and mah friend refuses to try other engines so lol
gamer ty
success ty very much everyone who helped
I need to display a bunch of spheres with a predetermined size and color at a bunch of different places in the world, without collision. I'm aware of GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);, but this creates colliders and instantiates a gameobject, when I just need the mesh since there are a lot of spheres. How can I achieve this?
Would it be bad to just use the default unity sphere? And just set colors with material color value.
Wouldn't need colliders.
how would I do that? GameObject.CreatePrimitive(PrimitiveType.Sphere); creates colliders by default and I feel like creating and immediatley destroying them is bad practice
Just instantiate a regular gameObject prefab, with the meshrenderer using the sphere.
Oh. I guess you asked for pings. @tulip mauve
Hi, I was thinking of a problem, that I dont really know how to properly explain (because I dont really know how it works tbh), but it was about how unity deals with the registration of listenners to callbacks via interfaces (e.g. The input system Map class Callback interface with actions callbacks or the event system with Interfaces for each of the UI actions) where you just determines a contract via the interface and the class will listen for when something happens.
Is this someway achievable or, as I think it is, is more complicated and takes more "behind the scenes" work by unity for it to work properly?
Does anyone know how to make a certain input a holdable button?
I’m making a platformer and it’s kinda ruining the flow of the game because I have to time my jump button every time I land, if I click too early it doesn’t input and makes for a worse experience.
Some help would be great
public class Example : MonoBehaviour, IPointerDownHandler
{
//Detect current clicks on the GameObject (the one with the script attached)
public void OnPointerDown(PointerEventData pointerEventData)
{
//Output the name of the GameObject that is being clicked
Debug.Log(name + "Game Object Click in Progress");
}
}
Was thinking of something like this
the event system uses either the Graphic Raycaster or Physics Raycaster to raycast from the mouse position and then it can just easily use TryGetComponent or something similar to call the interface methods
In this case I think it makes sense, but event system has other events that don't necessarily use Graphic Raycaster (I think) like the IMoveHandler and the ISubmitHandler
the EventSystem also has a reference to the currently selected object so it can easily call TryGetComponent to get the interfaces from the selected object and call the relevant methods
Yeah, I would want to know some more about it though... its sad to don't really know if this kind of architecture has a name or somethin... 🫠
there's literally nothing special about it other than what i've already described. the EventSystem uses the Physics Raycaster and/or Graphics Raycaster to get a reference to the object it should call the interface methods on
I mean to make a system that uses Interfaces to register listenners, but I think this problem has other Middle mans other than just the interfaces. In the two examples that I mentioned there needs some other step for it to work properly, so I don't think it's a easy task
you're implying that unity is doing something super special to call those methods on the components that implement the interfaces, but that isn't the case. the EventSystem has a reference to the object already so it's as simple as calling TryGetComponent on that reference to call the interface methods
you could use some sort of dependency injection and/or mediator pattern if you want to invoke events and have receivers react to the event without manually getting a reference to subscribe to the event
i dont understand
where am i wrong
can you share your !code correctly
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
does anyone know what the criteria for an object being droppable is? this is in relation to the IDropHandler interface.
like I have an inventory slot gameobject and want to fire the callback every time a UI object is dropped onto it but am unsure if this is correct use case (i think it is but im uncertain).
Ah, actually it's this one
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IDropHandler.html
Haven't played with this stuff for a while
The IEndDrag is actually just fluff which you usually just use to reset displayables
Oh, huh I swear there was a ton more documentation here. Maybe need to revert to the previous version documentations, but the idea is you need both an IDragHandler and an IDropHandler at minimum; everything else is just fluff. I'm pretty sure you can put an IDropHandler without an IDragHandler on your scripts if you just want that gameobject to receive drops callbacks without enabling it to send drag callbacks.
Oh, and the object needs to be able to receive raycasts, so UI stuff needs their raycasts can be blocked box ticked
someone here using mapbox API? i make a custom map on mapbox i put place’s with names then how to make it searchable?
So basically I have an emailing system in my app, like it sends an actual email through Gmail
But in the code, someone can easily find the "App Password" from that email.
Now ofc im not using my main email, im using a dummy empty email to send the messages out but I still dont want people getting that information
How can I hide it or encrypt it somehow?
im using navmesh and when an agent gets close to the destination, it slows down. how do i make it move at the same speed until it hits the destination?
You need to adjust the agent.StoppingDistance likely
okay ill try that
also i want the agent to immediately change direction when the destination changes, because right now it slows, then slowly changes direction
By change direction slowly you mean rotates slowly, right?
try also adjusting the agent.angularSpeed
okay
the stopppingDistance didnt change anything
i unticked AutoBraking too to see if that made it work
do i just set them in start method?
yes
you should have autoBraking off and you can set the agent velocity to keep the speed constant
ill try that
It would seem the key to it was the IDragHandler, wierd
im trying to make a grid, and im using a script, but its getting confused it keeps going back to the beginning after its created a somewhat grid
this is what it makes
heres my code
public class GridScript : MonoBehaviour
{
public float gridSize = 10f;
public float gridSpacing = 1f;
void Start()
{
LineRenderer lineRenderer = GetComponent<LineRenderer>();
int numLines = Mathf.FloorToInt(gridSize / gridSpacing) + 1;
lineRenderer.positionCount = numLines * 2;
float gridStart = -gridSize / 2f;
float gridEnd = gridSize / 2f;
int lineIndex = 0;
for (float i = gridStart; i <= gridEnd; i += gridSpacing)
{
// Add vertical line
lineRenderer.SetPosition(lineIndex, new Vector3(i, gridStart, 0f));
lineIndex++;
lineRenderer.SetPosition(lineIndex, new Vector3(i, gridEnd, 0f));
lineIndex++;
// Add horizontal line
lineRenderer.SetPosition(lineIndex, new Vector3(gridStart, i, 0f));
lineIndex++;
lineRenderer.SetPosition(lineIndex, new Vector3(gridEnd, i, 0f));
lineIndex++;
}
}
}
im assuming its the for loop logic
maybe use a for loop for each vertical and horizontal
You use one line renderer. Line renderers draw one continuous line
seperately
so id need to use lets say 2 linerenderers for vertical and horizontal
that makes sense
let me try it rq
any clue why code takes long as hell to complile
Don't know where to put this so I'll put it here since it has something to do with code:
https://i.imgur.com/vH10DmH.gif
wtf is going on with collisions?
Looks fine to me tbh
hey everyone, i am playing around with Netcode for GameObjects and want to deploy a dedicated server build to my Azure Windows VM. I can't seem to connect though. I added an inbound port rule for port 7777 but no success connecting. Does anyone have any resources on how to configure a Azure VM in order to allow connections?
Its NOT fine 😭
Which part? How is it supposed to work?
See the green hitbox highlighted at bottom?
the camera is supposed to stop moving when the skeleton hits that
but for some reason it happens way earlier
So how was any of that apparent from your original question
How are you detecting that the skeleton hits that box?
:///
The hitbox is a trigger
and the skeleton has a rigidbody trigger
attached to that trigger
is a script
I can send it
Triggers dont stop colliding objects I thought
Oh I misunderstood the issue, mobile issue
Yes, if you want help with code you should share the code
Okie dokie
1 min
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here is the method(s) it calls
IEnumerator DieAsync()
{
camScript.enabled = false;
yield return new WaitForSeconds(3f);
// TODO: FADE
SceneManager.LoadScene("MainGame");
}
void Die()
{
Debug.Log("Ran kill");
StartCoroutine(DieAsync());
}
Ignore the bad code, I'm doing a game jam and I don't have time to write good code lol
Does "Ran kill" print when you enter that box
Yep. That method is ran when it shouldn't be
Do some debugging and find out why
Log what is triggering the OnTriggerEnter2D, log the tag too
Ok
Wtf. Lemme check the collider
the red dot is where i collided, the green box at the bottom is where the LavaHitbox is
Is the lava not just colliding with the green box?
The lava itself doesnt have a collider
Also this.
I've tried making sure that the lava can only colldide with the player
Show me the inspector of LavaHitbox
The lava and the lava hitbox are separate objects.
What line produces this log?
Man, this switch statement in triggerenter is such spaghetti
but that wouldn't make sense cuz it has no collider ://
I dont have time for good code 😭
You already are logging the object
Its colliding with yea
If it was the camera then it would print that
Huh?
So is it not what i'm colliding with?
Yes?
But the script isnt attached to the lava hitbox
What did you mean with this then
Idk bruh
I know. What are you talking about
Isnt the script on the player?
hi lads, do know how to wrap around a world map, as in go from one edge to the other seamlessly? In a 2D RPG with tile maps atm. Currently, I have it where you basically have a duplicate map and move it right next to the current one, and they leapfrog each other depending on which edge you go on. I was wondering if theres a better way
The "other" variable gives you the object that you hit. You hit the lava according to your debug, not the camera
in principle, thats how you do it, you can always optimize to only "duplicate" the visible parts of the map
But also I dont know why u have a switch for the debug because you mightve forced it to only output lava
Ok. But that makes no sense... This script is connected to an empty with a hitbox that follows the player. That hitbox never touches the lava
Did the log say it hit the lava object?
yea
Ok on that trigger function, remove the switch because it is going to force the debug to only break when it hits lava from what I see. Have it print when it collides with anything other than the ground
Or when it collides with the box specifically
I assume the only reason it printed lava was because your character fell in there after it already died
Then it likely did. Maybe log the point of contact and use the overloaded second parameter in log to highlight the object in the hierarchy on single click of the log. cs Debug.Log($"...", other.gameObject);
Nope
The Die message is only sent when it hits the "Lava" though, from what I can tell
That's what I'm saying
It still prints die and lava without the character dying
Because your function is doing some switch statement and comparing it to lava
Did u show the whole trigger function before?
yea
here
The switch may actually be the problem
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Lava")
{
{
Debug.Log("Hit lava");
}
}
}
Yes that's what I was trying to say. You are only debugging when it hits lava..
This works much better
but how could the switch cause the character to die
before touching lava
?
Wait wasnt it supposed to die when it hit the green box, I thought u said that before
Use the compare tag function instead of string comparison
yea
Or that's when the camera is supposed to not follow
why?
And for a 3D globe, its just a 3D globe right. Though I do want it to look flat, even if you revolve around it. e.g Final Fantasy 7-9 Worlds
You probably hit something that could kill you or died from other means.
You need to debug more than just lava otherwise your character might die, not pause the game, fall into lava, and then debug/pause
But then I'd have to swap switch statements for if else statements
but if its a better solution then sure lol
Problem is, some times he just falls over and dies on ground. He doesnt even fall into lava but the game still pauses.
Does your debug still say lava
Then your collider is just messed up or the objects that your script is on is jumping all over the place
you'd only use a globe if you want to view it as a globe, or if you want to be clever about it, the standard way to do it on a tiled map would be to only render visible tiles and select tiles based on a looping index
the debug logs every collision
Pause the game after clicking to move, play frame by frame and see where your object is. The one that has the script
the first image is the game being paused
by script
What's the white thing in the lava, is that the game object that has the on trigger function?
Or where is that
Sorry hard to see on mobile I just couldnt tell
Debug.DrawLine(transform.position, other.transform.position, Color.green, 5.0f);```
It's likely the line would be extremely small since the game object and other are touching
Would be the same thing as just following the game objects position every frame
The line draws between origins, not contact points, so it should be visible
If anything, maybe you're looking at the wrong object - assuming the collider isn't on the skeleton.
I believe he said its on an empty object on the skeleton somewhere above
I'm assuming that's where the fault lies.
Yea that's why I'm saying to track the game object every frame, I'm thinking it's going flying around very often and falling down the tunnel into the lava very fast
Honestly now that I scrolled up I cant even find where he said that but regardless tracking it every frame will show the fault. It likely is just falling really fast
im having a issue where my bullets should be apearing as a constant stream but instead only spawn when i move the player. this is my code aswell ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Shooting : MonoBehaviour
{
public Transform shootingPoint;
public GameObject bulletPrefab;
private void Update()
{
Instantiate(bulletPrefab, shootingPoint.position, transform.rotation);
}
}
i put it in the update so shouldnt a bullet instantiate every frame? It was woeking and doing that before.
maybe the bullets are spawning every frame just not moving becuse they are stuck in other bullets.
they are probably crashing into each other, yes
i think you guys are right i took off the trigger and the come out now just too much come out lolol
Correct
[half life 2 ragdoll noises]
wtf
make it trigger again, do you detect when they should be destroyed anywhere?
why are they triggers is what I mean? Do you destroy them if they get "triggered"?
Good choice
Lemme see if I can find a summary for you lol
here
nah i have a trigger on the enemy so when they get hit they are destoryed i removed the trigger from the bullet since it was a mistake putting it on
bullets being triggers doesn't sound like a mistake..
enemies would be better off with colliders so they can't collide with other enemies and such
if you want your bullets to not collide with each other, make them triggers and in the enemy script detect OnTriggerEnter
also, exilon I have no idea why that's happening
are you sure nothing else in the scene has the tag of lava?
actually I would try commenting out the code that stop the camera movement and detects lava, maybe you already are doing it somewhere else and you just forgot?
i still don't understand your issue
My skeleton apparently collides with the lava
even though its not near it
have you tried making the lava inactive and see if it still happens?
because that would just mean you put the lava tag on something else
you should check what you're actually triggering, yes
Inactive?
Hey y'all! I am making my own version of Unity's PlayerPrefs, and i am using an encryption key to save and load data into a file. But right now the key is just a const readonly string. So if someone has a save file, they can share it. Is there any way to securely save a randomly generated key to use?
I thought about making another file, but that unneccerarely complicates things in my little script...
using cryptography to encrypt your save file and thinking an extra save file is "unnecessarily complex" seem like contradictory ideas...
yea, disable it
don't ask to ask; just write your question
here is the script
can you tell us what the stuff is?
So it has no collisions?
how do i control post processing 'color grading' value using slider
the entire object
from script
oh
well it's not really encrypted, i use the key and the data in a XOR operator
it's just really jumbled
what is the point
?
like, select it in the scene, and in the inspector, left to us name, click that tickbox so its empty
ye
now try running it
i could destroy this scheme with a very basic chosen plaintext attack
(or even just known plaintext, really)
if you have more lava objects, disable those too
ok i need real encryption then lol
now there is no collision
tried it but took me more time to debug then to make the entire script so i opted with the XOR operator
also my unity is being like a beach. it doesnt react with trigger thing. i told it to disable kinematic but it dont want to. but it print the debug
it detects nothing?
Nope. Disabled everything to do with lava
it's a save file for a mobile game i'm making. But since i am maybe making payments, i want to encrypt it somewhat ok to stop the general audience from messing with the save file
no collisions
what you've created here is the Vigenère cipher
I know but please do
Alr dead
maybe there is a tile in the grid that has the lava tag
did
i did not know that, cool :)
nothing
I need some feedback smh
there is still a level tho? you can still move your skeleton around and it collides with the ground?
you didn't disable everything right?
anyway, I don't really have any experience in the mobile space, but if you really want to prevent people from circumventing purchases, you'll need to store some data on the server side
where the user cannot manipulate it
because I want to see if there is maybe some other collider that is triggering it
yuh
Everything is normal
except the lava
which is no-collide
yeah i don't have the money to implement that. Plus most people will play it offline, so needing a constant internet connection is not really handy in this situation
do you know any encryption method that is secure enough?
sure, AES: but the problem is that the key has to live on the user's device
any way to jumble up the key?
sure, you can obfuscate it
just having a key file and a save file will already slow a lot of people down
alright
i'm not familiar with mobile devices, but i'm pretty sure applications can have storage that nobody else (including the file browser) can see
which would also put up another hurdle
android has built in protection since the new updates to the persistentDataPath
Ig i just have to make do
one thing that comes to mind is having a file that stores your purchases
idk for the life of me what to do
rather than encrypting it, you would sign it: the server would use a private key to create a digital signature
the game would then only accept your purchases as valid if the signature validates
asymmetric cryptography, rather than symmetric cryptography (the fun is increasing exponentially)