#archived-code-general
1 messages · Page 345 of 1
are you following the suggestions from https://forum.unity.com/threads/onmousedown-with-new-input-system.955053/ ?
If you need to stick with actual 2D physics buttons, I would add a singleton that does a Physics2D.OverlapPoint when you click the mouse.
Yes, basically I did exactly this:
(except programmatically, add an EventSystem + PhysicsRaycaster + InputSystemUIModule inside Start)
create an interface like IClickable and give it methods for "mouse down" (and "mouse up" if you want)
does anybody know how can I make my ragdolls leg point towards mouse or drag it by cursor?I'm trying to make a 2d football game thats why I'm asking.
use TryGetComponent(out IClickable clickable) to try and fetch an IClickable component from the object you hit with Physics2D.OverlapPoint
that's how I'd do it if I couldn't just turn this all into genuine UI
yyyeah so basically the "Do It All Yourself" solution
I'll think about it... thanks!
for now I'll just leave the old stuff and clean up unneeded buttons/axes in the old input system so that they won't interfere
well its not a do it all yourself soultion, just gives you more control when you do the cast or overlap your self and call stuff on a interface
this is what the game's doing right now, I've replaced all gamepad code to use the new input system because Unity's console packages really want you to use the new Input System for Xbox and Switch
but the mouse code is still relying on these OnMouse events
i've removed all calls to Input. and the only usage of the old input system right now is OnMouse
would remove all OnMouse events and only use the IPointerX versions
these aren't actually UI components
they're box colliders and sprite renderers
those will work fine with virutal mouses
they still work
I guess you can try to do it anyway
just add the correct raycaster
I'm guessing you have something that's getting in the way of the raycast. The Canvas probably has a GraphicRaycaster on it already
yes, there are multiple of them
its what i had to do to get virtual cursor working for a switch game, that used to use old input systme
i have no idea why
¯_(ツ)_/¯
surely this breaks the eventsystem raycast logic somehow, but why OnMouse works then is a mystery to me
why so many graphic raycasters?
I wish I knew, man
it should only be on the Camera you want to do the cast from
same goes for the 2 physics raycasters
no I've only added one, to the main camera
also will want only 1 event systme
This wouldn't be too much work overall -- you'd swap out the OnMouseDown method for your own IGotClicked method in each place that needs it
just kept trying between the 2d and the 3d versions, and also only one eventsystem in the entire game, linked to the input system ui input module
you wouldn't need to reconfigure anything in the inspector
but yeah would be so easy to just implement a new interface
then have 1 central place do raycasting and call the interface methods
could leave the logic mostly the same
hmmm I'll need to figure out which raycast logic/method the old OnMouse stuff is using just so I can do the dispatch manually with the new active input system handling
OnMouse... doesn't need a raycaster attached to a camera so how does it figure out which gameobjects are pressed 🤔
OnMouse... is older then the "new" ui system and those raycasters
huh
its from before 4.6 when unity got the UI system people use the most now, which is what incudes the EventSYstem, and raycasters
its been recommend to not use the OnMouse... stuff for a very long time now
i use almost none of them
iirc unity even warns about it on some platforms
ouchie
yeah if it's some cursed built-in checking instead of a normal raycast I can see why the new raycast thing breaks in this game
especially with all the graphics raycasters
pretty sure all it does is just cast from main camera, then call the message if its on the mb
would just start implementing something and deal with edge cases as you get to them
either your own interface methods and raycast or using the exisitng raycasters
or even building a custom raycaster for event system
You don't need a raycast to hit 2D colliders
Of course, this won't properly handle overlapping buttons (because this project is using 2D colliders for them)
If more than one Collider overlaps the point then the one returned will be the one with the lowest Z coordinate value. Null is returned if there are no Colliders over the point.
I guess it might sort of work!
only if the camera is pointing in the +Z direction
i would still use raycast over overlap point, so you dont have to deal with Z and what order they are in
a 2D raycast doesn't work like that
it doesn't fire from the camera into the 2D physics world
hmm I'll try checking for a left button press in some singleton, read the screen value, transform to world, then do OverlapPoint and print the name of the gameobject that got hit
if this will work correctly I'll hack my own event system then
a 2D raycast just starts from some 2D point and goes in some 2D direction
ah yeah looking at my code i was using the event sytstems RaycastAll when i needed to manually do things but want to consider if UI is blocking or not
Is there any way to use a Video Player with Timeline and have edit-mode scrubbing work? I tried the Default Playables sample from the Asset Store that comes with a video track, but that didn't work. I also downloaded the AVPro demo to see if their playable worked in edit-mode with Timeline, but no dice.
For context, I have a video file of a cutscene that I want to use as reference when rebuilding the cutscene in Unity with Timeline. It will be a total pain without some way to preview the video in the editor and overlay it on top of the game view. Overlaying a video works fine in play mode, but I need to see the video while doing stuff in edit mode. I can only find a bunch of old forum posts and scripts that don't work, but this seems like something you should be able to do haha
Hello, how are you ? I'm following a course on Youtube to make a dialogue system and I try to implement some features in my code. The feature I want to add is a way to show the speaker on screen in the face box, the screen or both. Actualy my code work for just one or but not both. Can you help me please ?
Here is the tutorial : https://www.youtube.com/watch?v=-mn3M52uOPc
My difficulty is to show both, because my code work only for one and I don^t know how to keep the same logic but modify to have both
Let's configure our characters to spawn in the scene and create the functionality for them to show and hide themselves from view.
Other Links:
-
Visit my webpage
-
See the rest of this course online
-
Discord Server
- https://di...
If I need to resume, I have a prefab with name of the speaker inside the same folder logic for each speaker.
Dialogue Ressources/Characters/FACEBOX/Name and Dialogue Ressources/Characters/SCREEN/Name
I've got this code who take the file path for the prefab object (charFacePathPrefab = Dialogue Ressources/Characters/FACEBOX/Name/Name.prefab )
private GameObject GetPrefab(string characterName){
string prefabPath = FormatCharacterPath(charFacePathPrefab, characterName);
return Resources.Load<GameObject>(prefabPath);
}
I'ld like to keep the same logic but modify the code to change the path to FACEBOX, SCREEN or Both. I don't know how to modify for both
and same thing for this code :
if(prefab !=null){
GameObject obj = Object.Instantiate(prefab, manager.charFacePannel);
obj.SetActive(true);
char_root = obj.GetComponent<RectTransform>();
anim = char_root.GetComponentInChildren<Animator>();
}
Where the manager.charFacePannel is the location to instantiate the prefab
CodeCopilot don't help me aha
!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.
https://paste.ofcode.org/fH8srXsqbTMKs8sqryTqy2 so iam generating a area with blocks(stone) then changing them randomly and replacing them with ores(eachone has a start and end spawn height) but in the code when i rmove the waitforseconds(.3f) it spawns a kind of platform inone height only. And when i put the waittime it exits as it should
Perhaps your BlockData component sets the position of the block in Start
Start runs before the first Update call, and that happens one frame after instantiation
in start its only creating the default area 6610
i dont understand the problem
Your code instantiates a bunch of blocks and then starts a coroutine.
I'm wondering if something is happening after the blocks are instantiated that's necessary for the ore generation to work right
such as, say, something done in BlockData's Start method
ahh nope
Perhaps the animations are trying to set the position of the root object?
that is, the object that has the Rigidbody on it
In that case, there is no reason whatsoever for the rigidbody to be making the animations look different.
Show your hierarchy and the inspectors for the objects with the animator and rigidbody on them
Hello. I am making an fps shooter and I have a problem with the weapon switching code. As seen in the video below, the weapons themselves work fine. But when I switch weapons, the knife stops working entirely but the gun works still
Here is all the code associated:
MeleeController.cs https://hastebin.com/share/esopaqisiv.csharp
MeleeDamage.cs https://hastebin.com/share/rorurepoxo.csharp
SwitchEquip.cs https://hastebin.com/share/usocizidev.csharp
Log if you're perhaps still swingingcs public void MeleeAttack() { Debug.Log($"Is swinging: {isSwinging}"); if (!isSwinging) { swingCoroutine = StartCoroutine(Swing()); } }
Anybody know anything about this concept?
public void MaterialTest()
{
materialInstance = new Material(material);
material.SetTexture("_BaseMap", texture);
Debug.Log("Material (" + materialInstance.ToString() + ") albedo map changed to (" + texture.ToString() + ").");
}
It pretty much hotswaps a material's main texture to a different one
for some reason it persists in editor mode
for all I know this probably isn't even a good or efficient practice for changing a material's texture or just an object's material altogether
Did you want to change the material of the new instance or the original material (assuming the original material is an asset)
Well, it would have to be the original because I'm not sure how to change a mesh such that it uses a new instance of the original material
https://discussions.unity.com/t/why-material-edit-are-persistent/7255
If you're doing this via code (you didn't specify), don't use
gameObject.renderer.sharedMaterial, instead, usegameObject.renderer.material
Assuming you're modifying the asset
it is the asset itself yes
Is there a way to only show the top part instead of all that other stuff in a Debug.Log for a Windows Server Build? Seems like alot of bloat for something I dont need to see unless I request for it lol.
That would be call the stacktrace. Maybe this might be useful https://docs.unity3d.com/Manual/StackTrace.html
Thanks I got it 😄
Glad the editor has the ability to discern regular logging and such with it.
Thanks again @dusk apex
private IEnumerator AttackCooldown()
{
isAttacking = true;
yield return new WaitForSeconds(attackCooldown);
isAttacking = false;
}```
When you deactivate this object while this coroutine is running, the coroutine will never end
so you will be stuck with isAttacking == true forever
In my game, the player can stretch their bodies to sling in a direction(hold space and a directional key. Releasing only directional key causes stretching to recede). I want them to not be able to stretch through obstacles. Currently, I'm attempting to achieve this by doing a SphereCheck at the face bone position (which is always at the front of the player).
Issues with this approach:
- The variable used to control the stretch animation's time still increases even if there's an obstacle preventing stretching which causes the player to 'snap' when receding
- If the player fully stretches and then changes direction, they can still clip through obstacles
See gif for a (hopefully) clear demonstration of these issues.
Here's the relevant code (ran every frame):
stretchTime += Time.deltaTime; //Not relevant to issue, just a variable for debouncing other logic.
GameChainData state = GameChainManager.Instance.GetState();
Vector3 inputVector = cam.transform.TransformDirection(state.inputVector) * 2f;
inputVector.y = 0f;
stretchVector = Vector3.MoveTowards(stretchVector, inputVector, 1f * Time.deltaTime);
stretchVector = Vector3.ClampMagnitude(stretchVector, 1f);
if (state.inputVector != Vector3.zero)
owner.lookVector = stretchVector.normalized;
if (!Physics.CheckSphere(faceBone.position, .5f, LayerMask.GetMask("Obstacle", "Ground")))
{
animator.SetFloat("StretchAmount", stretchVector.magnitude); //StretchAmount controls the time of the stretch animation.
}
How can I prevent the issues I've listed? A ray/sphere cast will fix the second one but I tried that and ended up with more issues relating to the snapping seen in the gif where stretchVector continues to increase even if there's an obstacle in the way.
Thanks!
I have problem with json file load
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public PlayerData playerData;
public void AddScore(int score)
{
playerData.Skoor += score;
}
private void Start()
{
playerData = GameObject.Find("GameManager").GetComponent<PlayerData>();
LoadPlayerData();
}
public void SavePlayerData()
{
string json = JsonUtility.ToJson(playerData);
SaveToFile("playerData.json", json);
}
public void LoadPlayerData()
{
string json = LoadFromFile("playerData.json");
if (!string.IsNullOrEmpty(json))
{
playerData = JsonUtility.FromJson<PlayerData>(json);
}
else
{
Debug.Log("No data found to load.");
}
}
private void SaveToFile(string filename, string json)
{
string path = Path.Combine(Application.persistentDataPath, filename);
File.WriteAllText(path, json);
}
private string LoadFromFile(string filename)
{
string path = Path.Combine(Application.persistentDataPath, filename);
if (File.Exists(path))
{
return File.ReadAllText(path);
}
return null;
}
public void DeletePlayerData()
{
string path = Path.Combine(Application.persistentDataPath, "playerData.json");
if (File.Exists(path))
{
File.Delete(path);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class PlayerData : MonoBehaviour
{
public int Skoor;
}
the files save to json but dont load
have you actually confirmed that the data was saved in the first place?
i found the file on my computer
and have you confirmed that the data inside that file is what you expect it to be?
yes
do you have any errors in the console
well there you go. i'm guessing you didn't bother reading the documentation for the methods you are using, so give this a read: https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
I read it but I dont understand what i need to change
Only plain classes and structures are supported; classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not. Note that classes derived from MonoBehaviour or ScriptableObject can be used with JsonUtility.FromJsonOverwrite as an alternative.
Question about cameras and UI canvas
I have a UI canvas in Screen Space - Camera mode using a camera A.
is it possible for a different camera B to also see/render the same canvas? how? I'm having a hard time with this
How is everyone using AI, LLMs, copilot, in their flow
@gleaming imp
I primarily use AI as an enhanced Google search, but I have to cross-verify with sources because the AI may be parroting incorrect information.
I set up my GitHub CI pipeline almost entirely using GPT to generate the boilerplate .yaml files, but I needed to hand-hold and do research on behalf of GPT so it could string together the correct commands. Even though it required significant oversight, it was still faster than me writing bash myself since I am not proficient with it.
It's okay in very small, defined scopes, and for solving problems for which there are many examples of solutions, but very bad at anything broader than the scope of two functions.
LLMs are good at drafting a lot of ideas and providing beginner-level guidance on many topics, but lack expert-level depth. It's basically a decent autocomplete in its current state.
at the end of the day they do not provide any measurable productivity improvement, in my experience they make learning and skill retention more difficult/slower and, in most cases, have a net-negative effect to my ability to continuously provide robust solutions to problems.
guys how do I loop a statement a specific number of times in unity?
is there a simpler way?
no, is this not simple enough?
for (int i = 0; i < 3; i++)
{
Console.Write(i);
}
guys how can ı get only blue color transform position Vector2 or Vector3
that green point player and and ı do not want ınstantıate or other methods in green circle
any idea?
then make a script and only attach it to the blue objects
what you mean
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
take a basic tutorial please
scripts are the code and objects are the things
you attach scripts to objects to make them do stuff
wow
Maybe a stupid suggestion, but I'd think that you could set the borders of the blue object and instantiate it. If it would instantiate in the green radius (aka. a certain distance from the center), then rechoose a position.
He's asking how to create the functionality. Not how to use it.
oh, well his question was pretty unclear
hes asking to get a position of an object
maybe unıty got method or somethıng
no ı want an area posıtıon I mean when ı ınstantıate an object It should be ın only blue area
ohhhh i see. my bad then. maybe use Mathf.Clamp
my englısh not very well btw
nw
or just set borders so your objects rigidbody cant exit it
assuming you have a rigidbody and collider
He's also wondering how it should be not spawning in the green circle. So math.clamp only shouldn't be enough I think
yeah true
then it spawns in the blue area yeah, but still the issue of the green spot
I think I had that problem before. I had a tutorial on how to fix it, but it was a long time ago
when player moves The green cırcle wıll move too wıth hım also
oh okay
This kinda does it, but not entirelly.
https://discussions.unity.com/t/how-do-i-make-objects-not-spawn-inside-a-certain-radius-inside-of-a-random-spawning-radius/291110
But he basicly "pushes" the spawned object
actually first step should push the spawned object and after that can clamp locatıon
even the spawned posıtıon out of blue area
ıt have to clamped in blue
if you want to check if a point is inisde the blue area, you make a composite check of "is it inside the red frame AND is it not inside the green circle", to make these individual checks you use a signed distance field definition of these shapes (cheat sheet here: https://iquilezles.org/articles/distfunctions/).
AH WAIT. I have a project with that exact functionality. Let me open it real quick
Or this haha
yea it is worth actually
if object in the green it will find other position
do we know how to check in a circle area?
ı know only for cube area
okay
i got no idea if this is the right place, but ima ask anyway
if you were gonna make a multiplayer game, which method would you use
ive found 3 methods so far
unities inbuilt https://www.youtube.com/watch?v=fdkvm21Y0xE
photon hosting https://www.youtube.com/watch?v=y69wBS13wwA
steam hosting https://www.youtube.com/watch?v=7Eoc8U8TWa8
is there any other "better" one that you would recommend instead
any help appreciated, i am pretty beginner level at the intricacies of coding (not so beginner that i need to be told that multiplayer is above my capabilities)
then you should not even be considering doing multi player
Is it possible to use Physics.BoxCast() outside of FixedUpdate?
i understand enough to say that if i want to push my boundaries and try and learn it i can
if i dont understand something thats fine, ill come back later when i can, but theres no point just saying "dont do that"
Or would it not give the desired result?'
I would counter that if you cannot evaluate the options yourself, then you are not
ive evaluated myself, i understand the principles of all 3 methods, im just asking for an outside opinion
Hello, I am in need of some help as I have no clue of what is happening here:
I have this Terrain (see image) where I added 4 high spikes for debugging reasons (orange vertical "lines"). My issue is that the actual heightmap modifiable space does not go all the way to the end of the terrain and I am very confused, can I force it to go all the way to the end?
then you should have reached the conclusion 'none of the above' because they all have major failings
you see how i said "is there any other "better" one that you would recommend instead"
this is because i figured there would be other methods because im aware
i asked for options not a smartass responce saying "f you"
@vivid halo that was also my initial experience, like babysitting an intern, but it's improved, GPT4 - which you can get free using Bing/copilot, seems much more capable, including live web search, and fleshing out complete structure/code.
Recently i've added a copilto to my IDE, supermaven, which adds context of your code, and further produces functional code autonomously.
i dont see the point of you saying dont do that, if you dont want to help me learn, say nothing, if you do, help me, either way, dont tell people their not capable of something because thats how you stop new people from wanting to learn and making new potentially great games
Multiplayer is not quite a beginner-level skill. I haven't done it myself, but I would focus on building the core game mechanics first so the multiplayer is not on the table until later.
i'm surprised there isn't already an off the shelf multiplayer package that does everything
"I'm surprised there isn't already an off the shelf game engine that makes the game for me" 😉
What a world that would be
Probably full of terrible, terrible games, moreso than today
to be fair there is an ai game maker, you draw stuff then add prompts and supposedly it does it all for you, i doubt the quality would be very good though
It won't replace game design knowledge
any of you guys know where i can find unity version 2017.4.9f1
well yeah
Even if you made a machine that could do everything perfectly, without good design it would still just produce bad games
it's fine, the world is already full of something for everyone
i think, inevitibly, the future is AI augmentation
any of you guys know where i can find unity version 2017.4.9f1
AI Augmention in the AR space, I would like more of
But this almost manic need to replace artists and engineers in games right now I don't get it
but it's also inevitable that AI will become more capable and autonomous
not that removes the ability for artistic expression
Unless we find a new way to make AI that is fundamentally different from the current GPT craze, then AI has plateud
We need another breakthrough or two
supermaven uses a different tech other than transformers, alledgely better
Allegedly
we'll continue seeing that, in particular agentic workflows
have you tried it in the IDE
I have not.
The thing with code completion tools is that it's very dependent on the quality of the code it's trained on
Most code in existence is bad code.
it'll take a lot of duct tape probably, but my expectation is it can do 80% of the work if you guide it well
if you pay for pro it adapts to your coding style
also claude artifacts is bonkers
Is there any good way to split code from client builds? My server and client are the same codebase with a switch in a scriptable object, now I'd like to not include my server code in the client build, is the only way a defined preprocessor var and #if blocks or do I have any other possibilities?
yeah, I just dont want certain scripts in the hands of users (includes them just making an edit to the scriptable config and being able to boot a server) 😄
#ifdef is your friend there
so no other way like excluding a full folder from building and just ifdef'ing the calls into that folder?
Well
The other way is to build your server client and your user client separate from each other
What many would likely consider "the better approach"
the server reuses a lot of the client code, so unless i wanna sync a shared repo between the two there is no good way for me to split the projects
Well if you have shared code you could make a git submodule and include the shared parts in both client and server project that way
It means you'd have to separate that code out into a library of sorts but I am guessing that is possible.
possible but from looking at it, it looks like more work than just ifdefing my way through it 😄
i am guessing the compiler ignores code files that are not used (excluded by ifdefs)?
As long as the code is valid in those files I guess. Otherwise they shouldn't be there.
wouldnt really help me if the calls are not made but the code is still compiled in there
Is there a somewhat easy way to run a check once per frame without using Update()? I need to inherit from a script without that functionality
How would you see that working?
You need to check every frame
Something has to call a method every frame somehow to make that check
You can create a MonoBehaviour that triggers an event once per frame and just listen to that in your script
That's potentially a ton of event propagation
That's not a bad idea, thanks
Thats true but he asked for an easy solution, I'd say depending on the use case its doable, if he gets performance troubles he can always circle back
I suppose so
I'm aware it's a mess but would this do the trick?
Never actually used events before, outside of premade stuff
On first glance it looks good, cant verify as I am on mobile rn
Wen discord AI runmycode
when you write any code worth running
@gleaming imp There's no off-topic here. Read #📖┃code-of-conduct
Hi again. I'm having a problem with melee hit detection. Upon left click, the knife will interpolate from swingStartPosition to swingEndPosition, carrying its big hitbox with it. Anything with the component "Entity" caught in the big hitbox will lose health. In the video I sent, the hitbox is clearly going straight through the entity but its not taking damage. The problem doesn't lie with the entity because the gun works fine on it
Here is all the associated code:
Entity https://hastebin.com/share/eyavewaray.csharp
MeleeDamage https://hastebin.com/share/aragupinos.csharp
MeleeController https://hastebin.com/share/ebisoyerom.csharp
is the sword able to trigger any kind of collision event on the entity at all? my guess would be missconfigured rigidbodies so the collision matrix doesnt trigger
The ball doesn't have a rigidbody but it has a box collider
does the sword have a rigidbody?
It also has a box collider
no rigidbody?
No rigid body here
two non-rigidbodies dont trigger events on each other
I can't make 2 box collider trigger each other?
not without one of the two having a rigidbody
Alright I'll see if it works
you can just give the sword a rigidbody and set it to kinematic
or give your enemy a rigidbody which he will most likely need in the future anyways (if you want them to move)
Oh wow it just works
Thanks!
Now I'm having a problem where in playmode the knife looks fine but when I do build the knife shrinks
Once again the gun is perfectly intact
so it looks different in a built game?
Yes
did you create your knife in blender / 3d software?
rightclick -> reimport on the model
Oke
also make sure any scaling you do in blender is applied to the transform
if there is any discrepancy between build and in-editor either reimporting or restarting unity is 99% of the time the right solution 😄
Noted 👍
Why does this barely move my character?
rb.AddForce(new(8, 0), ForceMode2D.Impulse);
rb is Rigidbody2D
8 is not much !
i usually go in the hundreds yeah
even with 100 it still moves the tiniest bit
maybe it's about the surrounding code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float dashCooldown = 3f;
[SerializeField] private float speed = 5f;
private Rigidbody2D rb;
private bool dash = false;
private bool dashOnCooldown = false;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
// Start is called before the first frame update
void Start()
{
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && !dashOnCooldown)
{
Debug.Log("Dash.");
dash = true;
StartCoroutine(DashCooldown());
}
}
// Update is called once per frame
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(x*speed, rb.velocity.y);
if (dash)
{
rb.AddForce(new(8, 0), ForceMode2D.Impulse);
dash = false;
}
}
IEnumerator DashCooldown()
{
dashOnCooldown = true;
yield return new WaitForSeconds(dashCooldown);
dashOnCooldown = false;
}
}```
@olive pebble
looks like it's still 8 here
yeye normal cause velocity and force is not the same scale at all
should i also do velocity on dash?
I do it that way but it might not be the most rigorous way to do
Plus you're missing on the different force modes, if you wanted yo use one
even this barely moves
rb.velocity += new Vector2(8, 0);
i tried both
it's probably coz of the surrounding code
because the main movement is okay with lower forces (5)
For some reason this custom event I made doesn't want to work. I'm attaching the MonoBehavior to the player but nothing in the function seems to work, is there somethin' I'm missing?
the thing is you are adding force on a single frame when dashing, as you are doing it every frame when walking
!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.
so how do i fix
public class SkillStormCaller : SkillData
{
public static bool leftRaised = false;
public static bool rightRaised = false;
public static bool bothHandsRaised = false;
public static float heightInput = 0.4f;
public bool Example;
public StormMono storm;
public override void OnSkillLoaded(SkillData skillData, Creature creature)
{
Player.currentCreature.gameObject.AddComponent<StormMono>();
storm.Loop += Storm_Loop;
}
public override void OnSkillUnloaded(SkillData skillData, Creature creature)
{
storm.Loop -= Storm_Loop;
}
private void Storm_Loop()
{
if (Example)
{
Debug.Log("Event Works");
}
}
}
public class StormMono : MonoBehaviour
{
public event StormMono.UpdateFrame Loop;
public delegate void UpdateFrame();
public void Update()
{
if (Loop != null) Loop();
}
}
}```
Is that what you wanted?
- you are overwritting your velocity with your horizontal movement
what's wrong
if you have a dash going on it gets reseted to the default run speed
huh
if you're are moving while dashing
even not moving the dash barely does anything
still think it's because of this line, cause if you are not moving then your velocity would be set at 0 every fixed update
rb.velocity = new Vector2(x*speed, rb.velocity.y);
resulting in your velocity being set only on 1 frame, then redefined with this line
depends on how you want to handle it
should i put dashing into a coroutine'
you can disable inputs while dashing
*I think I just saw why, I'm doing Player.currentCreature not storm = Player.curentCreature 
no, i want the player to be able to move while dashing
huh haven't thought about it for long but maybe don't set the velocity if it's higher than your run speed
you can check the abs of your velocity
you can make dash set your speed to 8 but input to still control the direction
let me do that
float x = Input.GetAxis("Horizontal");
if (Mathf.Abs(rb.velocity.x) <= speed)
{
rb.velocity = new Vector2(x * speed, rb.velocity.y);
}
if (dash)
{
rb.AddForce(new(8, 0), ForceMode2D.Impulse);
//rb.velocity += new Vector2(8, 0);
dash = false;
}
this works like a charm but dashing leaves some sliding and i want it to be instant
hold on i need to replace the sprite
mb chief
i stop moving as soon as i dash
the recording is a bit wonky coz i messed up the obs scene
Over time your inputs should take full control of the speed and stop the player if there is no input
maybe i should do MovePosition with Lerp
Why not just block horizontal inputs for a second and bring them back after that? What you have now with speed check is effectively that but with no clear timings
doesn't get rid of the sliding
rb.velocity = new Vector2(x * speed, rb.velocity.y); this line will stop sliding as soon as it is called
in that case you should indeed do a coroutine
btw you can get rid of your dash bool variable and just put a function instead
Just a quick question: is OnMouseDown/any 2D collider supposed to be intercepting UI events?
For example if i have a sprite that debugs to the console whenever clicked, and it's behind a UI button, and i click said button, and the sprite debugs to the console; is that SUPPOSED to happen?
If not then would I have to use raycasts or something to make sure this doesn't occur? EventSystem.IsPointerOverGameObject() surprisingly always returns true in this case.
jesus christ i accidentally made an infinite loop
💀
I don't think OnMouseDown cares about anything going on in the UI
it's its own weird (legacy) thing
💔 alr ty
I'm surprised that EventSystem.IsPointerOverGameObject() is returning true all of the time though
I use it to prevent clicking from triggering an action in the game world if my mouse is over the UI
I wonder if you have a transparent Image that's covering your entire canvas
If it's a raycast target, then your mouse will always be hovering over something
If you're using the old input system, select the Event System object in the inspector and look in the preview pane at the bottom
it'll show a bunch of information, including what you're hovering over
for some reason, the new input system's input module shows a lot less information
If many enemies are going to share the same patrol route, I'd make a PatrolRoute component that holds the list of transforms
The enemies could then reference one or more patrol routes
I've gotten a few user reports involving corrupted save files. It turns out that you cannot assume that writing a file to the file system will work (:
I'm planning to do this when I serialize the current save data:
- Copy save.json.bak2 to save.json.bak3
- Copy save.json.bak1 to save.json.bak2
- Copy save.json to save.json.bak1
- Write the new data to save.json
Then, when reading:
- Try to decode save.json
- If that fails, try to decode save.json.bak1
- If that fails, try to decode save.json.bak2
- If that fails, try to decode save.json.bak3
- If that fails, just give up
If something loaded, overwrite all invalid files with the successfully decoded data
Is this reasonable?
This was prompted by a bug report where a user's stats.json file turned into...
127 null bytes, followed by a +
You could just rename files though.
A problem I can see is that this touches every file when you save
True. That would avoid changing data on disk.
Better, you could have a file that keep track of the "latest" save.
I don't really understand how this could have happened.
I thought of that, but what if that file gets mangled?
This way, you do not need to rename them.
You can reconsitutate the file with guess at that point.
I guess I could just give up and read the files in order at that point
But, that would really be unlikely that it happens.
I would simply use order as you said.
Never overwrite the save I guess.
yeah, I could store:
- save.json <-- written every time you save
- save.index.json <-- tells you the most recently written backup index
- save.backup-X.json <-- written in round-robin fashion every time you save
so after five saves with three backups, you'd have:
- save.json <-- save 5
- save.index.json <-- tells you that backup-2 is the newest one
- save.backup-1.json <-- save 4
- save.backup-2.json <-- save 5
- save.backup-3.json <-- save 3
Corruption of save.json would be recoverable. Corruption of save.json and save.index.json would result in save 4 being restored
I could also check that, yes
Alteantively, you can increment the number each time and delete the oldest
private static void Serialize<T>(T obj, string path, bool onlyCreate)
{
EnsurePath(path);
if (onlyCreate && File.Exists(path))
return;
var data = JsonConvert.SerializeObject(obj, Formatting.None, Settings);
File.WriteAllText(path, data);
}
This is how I'm actually writing the data, by the way. EnsurePath creates directories if needed.
(I'm pretty sure the user's game or computer crashed...)
If this is such a rare case, you can also just create the backup. Never restore it.
A forum on internet where you explain how to restore manually.
True. I could then tell the user "hey, figure this out"
I already have buttons to open the log and debug-output folders
I'm currently fixing the more catastrophic problem -- if it fails to load the stats data, the game breaks 
it throws an exception and blows up the game controller's startup method
gonna add a TryDeserialize that can signal this failure more gently
Good idea. \
it's particularly embarrassing because the game only tracks one stat (number of times you've played) right now, haha
and I already had a similar problem: an older version of the game wrote an incompatible stats file to the same location, which I forgot about entirely
How do I combine two quaternions? I want to first apply q1 and then q2 but I need them combined so I only have one quaternion
Nop, Im not getting the expected result
Im inside the shader scope btw
like, doing it in a compute shader
so you have two float4s ?
yup
I've used this before:
https://gist.github.com/mattatz/40a91588d5fb38240403f198a938a593
it gives you a qmul function
float4's * operator just does element-wise multiplication
ah perfect, that seems to work
Hello, im currently trying to program a system, with which i can figure out, who the nearest player in relation to a finish line is.
Im using the code down below and have added the script to the finish line (the game object in the scene).
However, the finish line only checks for who the nearest player is when the game starts, and doesnt update, even though i have put it in void Update. I´d appreaciate any help!
using System.Collections.Generic;
using UnityEngine;
public class FIndFirstPlayer : MonoBehaviour
{
public GameObject[] AllPlayers;
public GameObject NearestPlayer;
float distance;
float nearestDistance = 10000;
void Update()
{
AllPlayers = GameObject.FindGameObjectsWithTag("Player");
for (int i = 0; i < AllPlayers.Length; i++)
{
distance = Vector3.Distance(this.transform.position, AllPlayers[i].transform.position);
if(distance < nearestDistance)
{
NearestPlayer = AllPlayers[i];
}
}
}
}
How do you know it isn't constantly updating?
If it's in Update, it will run every frame
what makes you think it isn't?
Also note that FindGameObjectsWithTag every frame will be inefficient, you could do it once in Start and reuse it for example
Actually I see the problem. You are forgetting to reset NearestDistance
It should just be a local variable
Im looking at the inspector(this thing) and it stays the same all the time, even though other players are closer
float nearestDistance = 10000;
void Update()
{```
Should become:
```cs
void Update()
{
float nearestDistance = 10000;```
because right now you never reset it at all
oooh, thanks for the tip, i´ll try that out!
make sense?
yeah, i see what the problem is
wait you're also forgetting to actually update the neartestDistance variable at all!
in the loop
distance = Vector3.Distance(this.transform.position, AllPlayers[i].transform.position);
if(distance < nearestDistance)
{
nearestDistance = distance;
NearestPlayer = AllPlayers[i];
}```
You need this as well^
that works flawlessly now, thanks a lot mate!
I don't like that our enemies look similar 😈
/jk
oh lol
btw you would have to convert the world position into a usable screenpoint
I forgot the process tbh cause I only did it once but I'm sure its out there
oh hey, I was just working on my "vision alert" system this morning
The simplest thing you can do is to do this:
- Vision Alert Marker <-- no components at all
- Arrow <-- has an image on it
Position Arrow above its parent
Now when you spin the Vision Alert Marker, the arrow moves around
that way, you don't have to set the position of anything
So I want to allow a user to add files to some folder in the built game's directory and for these files to be accessed by the game. What's the standard way to create a directory on build, and getting the path to it later?
I would have the user put it in the Application.persistentDataPath directory
For a non-circle, you'll have to do a bit of math
for a standalone game you can use Assets/Streaming Assets
Finding an angular position on an ellipse isn't quite as simple as doing it on a circle
I used the last answer on this page, which uses polar coordinates
StreamingAssets is good if you want the game to start with some files -- they get copied straight from the StreamingAssets folder into a folder in the built game's directory
I wound up using a mixture of that and just putting the arrow directly on the enemy
When the enemy is less than 75 degrees from the direction the camera is looking, I compute a screen space position and use that
I lerp to an elliptical position past that point
That avoids the weird behavior you get at 90 degrees
(screen space positions shoot off to infinity)
Ah I see.
Thanks.
Ends up like this in a build
hey guys, i have this code:
currentScreen = _screen;
for (int i = 0; i < screens.Length; i++) {
if (_screen == screens[i].type) {
screens[i].Activate();
} else {
screens[i].Deactivate();
}
}
}```
but when i try to execute it with the Button component, this function doesnt show in the list. why is that?
ScreenType is an enum
the zero-argument UnityEvent on Button (so, one that's designed to call functions with zero arguments) can only handle a few kinds of one-argument functions
I dunno if it can do enums at all
it can i think, i remember doing enums as arguments
because onclick events do not take parameters
but i think ive done button clicks with enums as parameters
you might think but I know
Button click events do take parameters (from the UI), it's just that enums are not supported
"Simple" types that you can fill from the Inspector are supported: int, float, string, GameObject, Component, etc.
Does anyone know why the unity Character Controller views this as a collision? the cube is at a Y of 3, the ground at 0, the height of the character controller is at 2. And i've tried moving the height test out by itself to make sure it was not some other collider near it
show the Transform?
It's at 0.08 not 3
oh the cube
Right now the height is 2, half the height is 1. Then the radius is .29 and the skin wiidth is 0.08 so you should be at a total of 1.37 units towards the ground
ignore that player transform above, here's the correct one using my test area, which has the ground at 1 not 0. interestingly its at 1.08, and the cube is at 3, but visually the collider is much lower
This is a probuilder mesh, it could literally be any size and shape
Also I can't tell if you're asking about it hitting the ground or the cube
the cube sorry
So how do you know it's being considered a hit exactly?
ground collision is working well, but like in that screenshot, its colliding with the cube
I can't go under it
Hi. Sorry to hijack the convo. Just got here and not sure where to ask. Working with unity VR and Oculus 2. How do find the way to increase run acceleration with the hand increase of speed and vise versa to slow a character down?
here's side orthographic view, with a default cube set to 3, this is a collision
ok well if you're t 1.08, you have to add 1.37 to that for half the height + the radius + the skin width
So that puts your player's "top" at 2.45 units.
If the cube is at 3 units, if it's a normal unity unit cube it should have a lower bound of 2.5
sorry the cube is grey its hard to see
so.. i'm not really sure tbh 😆
Can you confirm with OnControllerColliderHit
I am curious why you have a separate capsule collider though
Hey, im working on a FPS game, but I dont know how to code. Therefore, im relying on ChatGPT to write the code for my game, but its not working. There is one script and one script only in my project and its the player movement script. Whenever i press play on the game, WASD work, but for some reason it automatically moves the player backwards and doesnt stop. I have been troubleshooting for hours, and cant find a fix. All i know is that is has to do with that script. Anyone experienced this before, and if so, how did you fix it?
General question about how any of you would approach this problem, since I solved it in an unusual way compared to most other problems:
Problem: The camera must be rotated on X and Y axis (both yaw and pitch), but the root player object is only supposed to rotate on the Y-axis (player model should not pitch up or down when looking up or down)
Initial incorrect solution: Rotate camera by (X, Y, 0) and rotate root player object by (X, 0, 0)
Reason initial incorrect solution failed: Since the camera was a child object to the root player object, the X-rotation would apply once due to copying its parent (the root player) object's transform. A naive follow-up solution rotate the player to align with the camera, but this would in turn rotate the camera as it is a child object of the player, causing a cycle of extremely fast, endless spinning)
Revised solution: Rotate camera by (0, Y, 0) and rotate root player object by (X, 0, 0)
Why it works: The x-rotation applies to the camera and the player while the Y rotation only applies to the camera, the child object.
I'm going to guess that your code reads something like:
if (s is pressed)
{
MoveBackward()
}
Without any logic to stop moving backward when S is un-pressed.
i send a pic of the code
!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.
It absolutely goes without saying that you cannot rely primarily on GPT to code. You should take time to learn how to code, and use GPT as one of many resources in which to learn. Using GPT to solve problems can introduce many problems of its own if you don't know how to validate whether or not the code is working.
Your very problem is evidence of this.
@leaden ice btw I figured out whats causing it, its the step height. which unfortunately I'm not sure how to fix. I want a high step height because I want the player to walk up large steps (retro look, chunkier scale), but not get stuck under things you should be able to walk through
this says nothing about artificially raising your height, either
https://paste.ofcode.org/inUyfTNmzdjcvccpEwewJL idk why it keeps building the same value
ignore the true/false
and where are you logging that value from?
in the generateRandomOres
float t = Random.value;
Debug.Log(t);
This?
yes
I see that you have some code that initializes the RNG commented out
are you sure you saved before you ran the game and got those logs?
becuase you have to call Random.Next() for the next value
no, Random.value produces a new random value
just use Random.Range
you're thinking of System.Random
yes 100 percent
are you using it all in the same frame?
it will give the same value over and over in the same frame
no
only if you reset the state every single time before you use it
randominitstate?
Random.value is a property. It runs a function that generates a random value and updates the random state
yes -- notably, Random.InitState(System.DateTime.Now.Millisecond);
If you ran this before each time you read Random.value, you'd get the same value out every time
yeah because i wanted a seed system and thought problem is bcs of that - commented out due to that
ahhh yea unity enginge's changes the seed for you
or whatever, i always forget there's two Random classes lol
it's not that it changes the seed for you each frame
iam not calling it once
when you ask for a random number, the RNG's internal state updates
i dont change the seed in any code i think
you can prove that you don't by searching your code for Random.InitState and Random.state
hotkeys pls
ctrl-shift-F generally does a project-wide search in your code editor
got it i had another file idk what i did f myself
If you need deterministic RNG for this generation process, you shouldn't use UnityEngine.Random at all
Anything else that uses it will screw up the internal state
yeah thanks tho
You can create a System.Random, or you can use Unity.Mathematics.Random https://docs.unity3d.com/Packages/com.unity.mathematics@0.0/api/Unity.Mathematics.Random.html
"deterministic RNG"....that made me chuckle a bit even though it is a valid question
Both of these will let you create your own RNG that only gets used by the generator
You can also save the current RNG state and restore your own, use it, and then restore the original RNG state
but that's a bit of a pain in the neck
Hello everyone. Does anyone know how I can get the play-head position from an audio source? For example, how do I check the elapsed time of a song, to make something run after a certain position in the song is reached. Say a song is 3 minutes, and I want to debug.log "hi" into my output after 2 minutes of elapsed time.
How can I do something like this?
Non-random randomness
I’m not really aware of “atomic writing” for filesystems
Where did you copy that text from?
this is talking about the general concept of an atomic operation, yes
theres no direct atomic write method in C# like python for example
i'm not aware of python being able to do this
If anything, the file system needs to provide an atomic operation, all an application can do is fake it internally
I see. Yes, writing the file and then clobbering the original is a decent idea.
Assuming that the write actually flushed to disk, it gives you less room for an inconsistent file state
that holds for any kind of atomic operation. It fundamentally depends on the physical reality of doing it. So it’s necessarily a hardware feature.
note that this is not doing anything special that Python provides
the C# implementation would be almost identical, save for syntax and name changes
That’s not really guaranteeing anything though. It can still fail
Makes sense
assuming the file makes it to disk, a crash sometime during the file move should be recoverable by the filesystem (thanks to journaling)
directly overwriting the file means that you're in danger the moment the file gets cleared, until you finish writing the save data
I'm not sure if I can reasonably test this, but I suppose it would be easy enough to implement
private void PerformConditionCheck(ConditionData condition)
{
ConditionValidationData conditionValidationData = new ConditionValidationData {};
conditionValidationData.condition = condition;
Debug.Log($"ConditionValidationData created with condition {conditionValidationData.condition.conditionName} instance ID: {conditionValidationData.condition.GetHashCode()}");
Debug.Log($"PerformConditionCheck: {condition.conditionName} instance ID: {condition.GetHashCode()}");
}
What are possible reasons why the hashcode of these two references of the same Condition class have different hashcodes?
This is an XY problem, my real problem is
guiConditionData.condition.targetCharacter.conditions.Remove(guiConditionData.condition)
this fails to remove the condition, when they should be the same condition, and I dont know why or how to debug to find the reason why
They're classes, classes are a reference type yes?
how is ConditionValidationData defined?
did you override GetHashCode?
and what is the type of conditions?
Conditions are classes, not structs
im now staring my own stupid decision in the face
yeah that'd make them not equate
If I undo this sneaky clone, I am going to have a new problem occur which is that I need a clone of a condition in a different circumstance 
but I think I can solve that
with calling it manually instead of doing that hot mess
Maybe you need to "copy on write"?
where you copy the object when you need to modify it
The problem Im facing and don't know how to solve is if I DONT do that clone method, somehow every condition is the same condition class
and like I tried to solve it just now and its still happening and I don't know why or how to fix it 
if (IsConditionValid(conditionToApply, targetCharacter))
{
conditionToApply.targetCharacter = targetCharacter;
ConditionData uniqueInstance = new ConditionData();
uniqueInstance.CloneConditionData(conditionToApply);
targetCharacter.SetCondition(uniqueInstance);
// Clear the current condition to apply for the next entry
conditionToApply = new ConditionData();
initiative.RequestUpdateSubscribers();
}```
why was this insufficient to create a brand new unique separate class?
I made a whole new instance of the condition data, cloned all the values to it
perhaps conditionToApply is the iteration variable of a foreach loop?
assigning conditionToApply = new ConditionData(); wouldn't do anything to future iterations
Oh uh I can link the entire code but this is an editor window gui panel thing
otherwise, i'll need to see some more code -- the script this block is from, as well as the definition for ConditionData
Sure, let me find the code dump link
or is there something specific that is more useful
I cant find the link to the code copy paste websites
My player flips whenever I move: https://pastebin.com/HhdQhHxh
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I will try that, good timing 👀
NP
https://pastebin.com/SQQuzdV0 @leaden ice
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.
representation is immediately suspicious, because that's a reference type
(it's a GameObject)
This is why I had that clone method before, the clone method COMPLETELY solved all of these issues, but now I can't use it, and my attempt to remake it has failed
This worked to solve all my problems but I don't know why it did
Hello
this is so frustrating and I'm honestly too far gone into crisis now by how frustrated and distressed I am over this that I am not able to actionably work on this any further, which in and of itself only highens my distress.
Thank you for helping me on this but I have to shut everything down now because I am having a nervious breakdown
Alright
I'm not able to disenguage like that, I will never ever be happy or calm again until I solve this 🫠
but being like this makes it impossible to solve
so its a recipe for a hellish vortex into crisis
(programming without mental health is a bad)
why don't you jsut go for a walk or touch grass
When you're looking at the problem again, I'd look carefully at the timing of the original Clone() vs. the new CloneConditionData call
I've tried, every moment the entire time I will be spent ruminating, spinning my wheel, focusing on the problem, focusing on why its a problem, focusing on distress, focusing on trying to solve it. I just don't winde down like how other people seem to be capable of
public class ConditionData
{
public int dc = 10;
public AbilityScore saveType;
public int duration = 10;
public string conditionName;
public RulesD20.Condition condition;
public ConditionSaveContext saveContext;
public Sprite conditionSprite;
public GameObject representation;
public CharacterActor targetCharacter;
public DiceRollResult save1;
public DiceRollResult save2;
public ConditionData Clone()
{
return new ConditionData
{
dc = this.dc,
targetCharacter = this.targetCharacter,
saveType = this.saveType,
duration = this.duration,
conditionName = this.conditionName,
condition = this.condition,
saveContext = this.saveContext,
conditionSprite = this.conditionSprite,
representation = this.representation,
save1 = this.save1,
save2 = this.save2
};
}
}
public class ConditionValidationData : ValidationStackBaseAction
{
private ConditionData _condition;
public ConditionData condition
{
get => _condition ?? (_condition = new ConditionData());
set => _condition = value?.Clone();
}
}```
This is how the Clone code worked before I messed with it
this worked to solve all every of my problems
except created a new problem wherein I cannot remove my clone because its not in a completely different circumstance the same
where is ConditionValidationData in here, if anywhere?
public class ConditionValidationData : ValidationStackBaseAction
{
private ConditionData _condition;
public ConditionData condition
{
get => _condition ?? (_condition = new ConditionData());
set => _condition = value?.Clone();
}
public override Guid Attacker { get; set; }
public override Guid Target { get; set; }
public override void UpdateChatlog(bool isSuccessfulSave)
{
if (chatlogContent != null)
{
chatlogContent.UpdateChatSetSaveResult(isSuccessfulSave);
}
}
}```
its a higher level container that contains the condition
I'm asking where in here ConditionValidationData is being used. You're cloning a ConditionData in this block of code, and I see that you used to be cloning the ConditionData when assigning to ConditionValidationData.condition
uniqueInstance gets passed to targetCharacter.SetCondition. Does that eventually wind up assigning to ConditionValidationData.condition?
Sorry I misunderstood.
It's being used here:
this version of the code is after I messed around failing to fix my issue though, Ill try to revert it
This is also part of my problem
is that my codebase is paralyzingly massive
but I'm too stupid to write it any slimmer, I need everything to do what I need to do and I dont know how to accomplish it with any less
so like even to show you any of the things you're asking for as sprawling walls of text
like 50 methods deep across 5 classes
and I try to refactor to make that not the case
and all I get is now its 60 methods deep across 6 classes 🫠 anyways
My codebase has grown so large that I no longer remember or comprehend large swathes of it that I wrote weeks or months ago
so im fucked when anything goes wrong
Are you using version control?
Yes, github
I can undo my changes but my problem exists in the past
unless you're trying to suggest something else
Good commit messages can help you to remember why you did things a long time ago. If you don't have those, then you should certainly start writing them
(and, more acutely, this means you can cleanly undo all of your recent changes, yes)
I need help, my character just spins when I move, I have Newtonian physics added(A lot used from Sebastian Lague) https://pastebin.com/HhdQhHxh
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.
Ah okay, that's already a means of thinking I haven't ever even done. To me all github is is a place to store code and roll back to earlier code.
Like, maybe I am not understanding what you're trying to teach me
If I go into my old code, and I don't understand my old code, how does/what does gthub do to solve that? It will have comments on commits but its not going to explain my own code back to me? Maybe?
Like if I am confused by my own code, I don't understand how/why github fixes that
my brain is fried I think I linked the wrong code entirely in that screenshot
Your commit messages should describe what you accomplished with that commit. You should also describe why you made those changes if it's not immediately clear.
if you cannot understand your own code or why you wrote it, you should 100% be writing better comments
Git is a version control, so you are correct that it won't directly explain your code to you.
However if you use version control from the very beginning of your project, then every line of code must be added/modified/removed from a particular commit. Combine that with a good commit message, it means that you can use features like git blame, or simply viewing the timeline of a particular file, to know that which commit added the line, and you can read the commit message to understand the context of that code a little bit better than having literally nothing.
and yes: good XML doc comments will let you document your code in a way that your IDE can show to you when you hover over types, fill out arguments, etc.
This is particularly important if you have a lot of complex machinery.
git blame is very useful for reminding yourself where a line of code came from
(although I just broke that by doing a few project-wide reformattings)
I have PlannerActions and StateActivitys and ModuleTargetedActivityDatas. I have a pretty strong grasp of how all of the parts of my game works, but I do have a little over 500 scripts (defining more like 600 types). A few good comments can really help to keep things in order.
(it tells you which commit most recently changed each line of code)
doing a huge reformat means that most lines were now most recently changed by the same commit
Yeah, I also need help with some code. Unity broke so many times for me. I am new to the Unity forum...
Start by explaining what you need help with, and what "unity broke" could mean
Yeah git doesn't replace comments. Besides API comments, you should also have comments to explain the "why" of your code when it is not immediately obvious, or simply impossible to know by reading the code alone (eg fixing an upstream issue)
for example, I have a line that looks like this
_ = MainMenu.Instance;
But git is very useful for cases when the code was obvious in that particular commit, but stop making sense after later changes.
(i forget if that needs a var; i'm not at my computer)
This causes the main menu to be instantiated from a prefab
It's very non-obvious, so I put a comment explaining that it actually has an effect
Sorry, I may be in the wrong chat... This code that I am talking about seems like it was for a beginner code.
If YOU are a beginner, then post in beginner
Best to just post the question and be redirected as needed though
No reason to be rude.
Ok. I am new here...
I am not sure how that is rude
No worries. I'm just saying post where you feel comfortable
It is more about where YOU are in the journey than what the code is
I just seemed a bit harsh for a simple mistake, but maybe that's just me.
No one made a mistake. They asked where to post
I was explaining how the channels are divided
Oh, then my bad.
Ill study this all over tomorrow and try to internalze it when its less late in my time zone. I think moving forward I should remove my clone hack thing and instead try to figure out why somehow everything is referencing the same class
Its not just you, I have them blocked for their harsh language
What? What a rude thing to say. I apologize.
I will say that bunp is generally extremely rude to people most of the time. So that sounds about right that they would say something horrible like that
Best for me to just block in return I guess
I now understand thank you.
I am an intermediate coder, but I will ask anyway.
Okay, this channel is for helping people, not arguing, I understand that I kind of started it, but still.
You did not start anything. You are okay. I thank you
I would consider you to be a programmer, and not a "coder", it makes it seem like your skill level is less than it is.
Either way, opinions are opinions, I should respect that.
I am doing an RPG, and I am trying to instantiate the numbers when dealing damage. It is not showing up and I also had effects facing the wrong way.
It's not about telling someone they are a beginner or not, it's also about the quality of help they will receive in each channel. People who help in #💻┃code-beginner for example, have generally much better ways of words to explain concepts to a beginner than someone who usually helps in the other code channels like me. Sometimes when a question becomes clear that it's way below the level indicated by the channel, I just stop engaging because I simply am not good at helping stuffs like "explaining what a variable is." Directing people to the correct channel means not only the questions are in the correct place, but they will also get much higher quality of help. Don't take that as a sign of insult, I can guarantee you most helpers do that not because they are trying to make you feel bad.
Do you have custom sprites for the numbers?
how do the numbers appear: text or sprites?
are you pooling the text?
Yes. the numbers are with TextMeshPro.
show your code. did you follow any tutorial? i know there are dozens on this topic . . .
Then they wouldn't have to be instantiated?
Unless you're using it for effect, and not ui.
to be fair, I am following a tutorial, and it is supposed to be for UI. but I have effects as well.
I feel bad now.
you're gonna need to show relevant code
that's fine. i asked to get a grasp on the situation. did you compare their code with yours?
Sorry, I don't quite fully understand your situation, so I'm just trying to ask general questions.
I am.. one moment.
Yes, and nothing is showing up, and I will show regular code.
One moment.
Share code like this btw
📃 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.
So, let me try to understand, you're trying to create an effect with text as the damage you do to the enemies?
if you are 100% sure your code matches 1-to-1, then check that the inspector and GameObjects are setup correctly . . .
When you attack the enemy, or get attacked, the numbers will show the damage dealt.
Yes. It is hooked correctly.
Did you modify the prefabs transforms?
Not really.
still waiting for the code. that's the first place to start . . .
I am. I have a pastebin.
then we can deal with inspector/prefab setup . . .
This is the DamageUI: https://hastebin.com/share/zafaqohuno.csharp
We're sorry, but the contents of the bin could not be found, or it has been deleted.
Wait. I got a pastebin.... went to the wrong one. uggg.
everything is there . . .
public class CharacterDamageUI : MonoBehaviour
{
[SerializeField] TextMeshProUGUI damageText;
[SerializeField] float lifetime = 1f, moveSpeed = 1f; float textVibrations = .4f;
void Update()
{
Destroy(gameObject, lifetime);
transform.position += new Vector3(0, moveSpeed * Time.deltaTime, 0f);
}
public void SetDamage(int damage)
{
damageText.text = damage.ToString();
float jitter = Random.Range(-textVibrations, textVibrations);
transform.position += new Vector3(jitter, jitter, 0f);
}
}```
It works now.
first issue i see is calling Destroy every frame . . .
gonna need to see what actually instantiates it too
Oh... I am posting that... hastebin is not working.
but yeah, that Destroy call should be in Start not Update
from the snippet above, i removed the Start method because it was empty. that is where Destroy should go . . .
It instantiates a text
so the text does appear? does it move?
Nope. it does nothing.
if this is UI, you shouldn't update the transform but its RectTransform . . .
yep, the tutorial calls for the instantiation of a canvas with UI, so yes this is UI.
Is lifetime set to 1 in the inspector as well?
Yes.
I was honestly trying to find a better way of making the text show when dealing damage.
I veered from the tutorial a bit.
I am not seeing the instantiate code. Are you saying the OBJECT is actually instantiated, you just can't see it? Sorry I'm in and out so much. Multitasking
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I do not know why this says java, but this is the code.
The "Character Damage UI" value, is what supposed to instantiate the canvas. Also, I do have another issue.
instantiate the canvas? the canvas should already be in your hierarchy. there is no need to instantiate one . . .
This created a seperate canvas. and showed UI text on it.
This is a tutorial, but I will veer from it... it is not doing me any good with this code.
you can just have the canvas in your scene. no need to create it at runtime . . .
Hmm... I see. I will find a way to instantiate it and set it inactive.
Putting the code on start did help.. thanks. it is still not showing up.. I feel very stupid.
But, I am here on a bigger problem though....
when the damage text is instantiated, does it appear as a child of the canvas?
Hmm yes!
weird, i don't see where you parent the damage text to the canvas or where the canvas is created at all . . .
I created a canvas, and the text is under that canvas in world space. I am instantiating the whole thing.
The Prefab is a Canvas with Text under it, sorry, that is what I mean.
wait, what? damageText1 prefab is a canvas, not a GameObject with a CharacterDamageUI on it?
Yeah, It is a canvas object with UI in it.
Yeah, that tutorial is on something else.
Also. The other problem.. where do I go, if my game keeps crashing.
I was also using git as version control.
When you say crashing, do you mean the program actually closes? Or just freezes?
define "crashing" because 9 times out of 10 when people say that here they actually mean it just freezes. and that is usually caused by an infinite loop
BOTH
Freezing then. I would say infinite loop like box said.
Got any while loops in update? That is a common one
I have also forgotten a yield in coroutine loops too, which caused it
I have a lot of for loops.
what code did you add or change before it started freezing?
I am so sorry... I do not know how to ask for help..... This is a little intimidating.
It's fine, at least you're getting help.
I actilly sarted when I had created an inventory script and I was trying to create the menu, and it actually closed and froze on me. It is incomplete, but I will show the script.
No need to be sorry. You are all good
You have been doing very well in listening and responding to questions
Sorry, just making sure, but did you ask for help and get missed? It happens sometimes
Yeah, but I can wait, I'm taking a little break from working on my game for the afternoon, so you're all good.
https://hastebin.com/share/secimikuti.csharp Inventory Script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
First problem was that I tried to create a menu that you can switch from viewing stats, to items. I was making the UI and it froze on me. I do not know if it was even the code, or my level.
For context, I am making a top-down RPG. I got the basics down(only thing i need is to handle how to use magic and items in battle and I am good).
Sorry about that.
I sent Unity a report about it.
You're good, I'm just having problems with simulated Newtonian physics, foux gravity, and movement playing nice with eachother.
movement, what type of movement?
Planet-based movement, using foux gravity temporarily until I can get my simulated gravity I use for my planets to work with my movement script.
you are moving them with the transforms correct?
Yeah, here's the file for anyone who's interested https://pastebin.com/HhdQhHxh
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I think.
are you trying to make them rotate while moving?
Well, I'm trying to change the transform.up to face the center of the planet.
Other than that, no.
Oh, sorry, you are saying its a direction issue, not a rotation issue.
Can you explain what I did wrong?
get the direction from the center of the planet to the player, then set transform.up to that direction . . .
you should check #854851968446365696 for what to include when asking for help. because you haven't really explained what isn't working the way you expect
Are you facing in world space or local space?
That's not when I originally asked for help, I've asked twice, and didn't get an answer, so sorry for you not liking the way I asked.
cool since you don't want to provide context for your issue i won't help you 🤷♂️
"here's 200 lines of code. explain what i did wrong. no, i will not say what isn't working the way i want"
And I thought ChillHound was saying that it was a direction issue, and he found the source of the problem, so my bad.
its maybe a direction issue, so the next problem, is the object a child?
I have, twice.
Can you link to it?
I see this, but it doesn't say the exact issue
#archived-code-general message
I assume there is something far above, but when I looked, I could not find it
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.
It flips whenever I move, I think it may be an issue with how I calculated the directions when moving.
do you have a reference to the objects direction?
Vector3 gravityUp = (transform.position - transform.position).normalized;
Vector3 localUp = transform.transform.up;
DirToPlanet = (transform.position - rb.position).normalized;
transform.up = DirToPlanet;
This needs to be the center of the planets position minus your position
do you have a constraint on the Z axis
I'm wondering if it is the MoveDirection fighting with the AddForce calls
MoveDirection is for Kinematic rbs, and is basically teleporting
I have some questions about nav mesh, I understand how to bake a surface mesh and agents etc, i just dont understand how to set certain walkable slopes, or if i want an agent to be able to fall off the side of something
No.
Is there an alternative that would work for non kinematic RB's?
you should really add debugs to your code, because you'd very quickly see where issues are like
transform.position - transform.position
Usually just AddForce or setting/modifying velocity directly
I do, all the time, just get rid of a lot of them, because they conflict with other logs.
Hmm, actually DirToPlanet is quite odd
You are doing THAT objects transform position minus THAT objects rigidbody position (which should be the same)
Oh, that's just.. Thanks.
well debugging wouldve quickly showed u that the vector was 0
Sorry for the hassle.
Okay, thanks.
Oh, laggy from going back and forth. Missed all that.
Glad it is figured out
Agreed. I as about to say, he can move the rigidbody by RB.MovePosition, or using rb.velocity.y.
Vector3.up, try that.
It wasn't that, but it was related, I feel so dumb, the RB is the players rb, so when I did transform.position - rb.position, it was 0, because the rb is the players rigidBody.
Thank you everybody, and sorry for wasting your time.
hmm, I am sorry about that... I thought it was a position issue, honestly
No need, it happens, I can relate. I can't instantiate a text object properly and my UI is not functioning.
No, your all good, I just feel like an idiot for not remembering what the value of rb was, even thought I wrote it.
🤦♂️
I am honestly intimidated by this chat, so I feel you
i mean, a rb field inside of the PlayerController script sounds like the player rigidbody . . . 🤷♀️
I'm similar, just use it usually when needed.
Yeah, that was my bad.. Sorry.
if not, then i'd expect a more concise field name . . .
not a problem. i knew you'd get there . . .
It happens, I was stuck on a code for 3 days and found out that the execution order was wrong in the code.
Really sorry if I contributed to that. I really just meant to say pick the chat you feel matches YOUR skill level. But it's not a big deal. I meant it to be nice haha
I was so focused on it being a rotation issue, that I ignored the most basic errors.
Honestly, i thought it was a rotation issue. I had a similar problem, and found out that i had to move in the world space axis and constrain my z axis.
It is fine, It takes a while for me to know peoples intentions, and i get misunderstood alot.
I'm just surprised fresh eyes couldn't figure it out at face value(Not trying to be mean)
Again, thanks everyone for deverting your time to an issue as simple as this.
I had to use the rubber duck method several times and talk to family.
the general and intermediate channels hit different. there is a certain level expected when asking help as small, common errors can be debugged and fixed personally. it's harder to hold a person's hands because of time and availability . . .
though, both of you are fine. it happens. at least some of your problems/issues are fixed . . .
Ok. Not the instantiating the canvas issue though.... At least the Start option, stopped the null reference error. It is still not showing up.
with yours: i'd focus on one system/mechanic at a time. if the inventory crashes, hide all those GameObjects until you can fix your damage text issue. then move back to the inventory . . .
Yeah, that is what I am doing. I had a major Unity crash and I was trying to figure out what the problem was... It crashed several times, but one involved Git.
i just need some help with cloning a 2d array of a class called cell right now im using gm.board.Clone() as Gamemanager.Cell[,] but some how when i change this it still changes the original one
https://www.youtube.com/watch?v=HGQYu-L2NOw
Am following this tutorial and I'm getting a couple errors
Patreon: https://www.patreon.com/user?u=28674164
Ko-fi: https://ko-fi.com/gregdevstuff
Twitter: https://twitter.com/GregDevStuff1
Discord: https://discord.com/invite/6Hav9Hc
Join this channel to get access to perks:
https://www.youtube.com/channel/UCZAenDNR0vQRqQAHiQ6JXgg/join
The first one I get when I hit play and start up the scene, the second I get whenever I try to click on a non-traversable node
main three scripts I'm using
How to properly post !code (some of us do not get embedded collapsed text files)
📃 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.
You'd use the large code blocks guidelines (inline would be for small snippets of code only)
so im looking at a question on stack overflow and theres different answers, should i just try understanding one of the easier ones or complex ones so i could learn more
i started unity yesterday if that changes ur answer
The first error (assuming it's the first - fix the errors from top to bottom to avoid false positives) suggests that the position was not within the range of the multi dimensional array cs grid[positionOnGrid.x, positionOnGrid.y].gridObject = gridObject;
Where the position on grid has a value that was greater than maximum x or y
That I got, but I'm trying to figure out why any of my scripts would by trying to interact with a position outside of the grid
Why not log the positions it's trying to access, or attach the debugger to get the full context
I've been trying to figure out how to do that ngl
How to do what exactly
Debug.Log?
That should be the very first thing you ever learn in Unity
How to specifically log the positions that it's trying to index
is there a way of serializing types on a monobehaviour with the functionality that you could somehow drag and drop type values like you would for a transform in the inspector? i would like to be able to instantiate objects of said types on start/ awake
Use a ScriptableObject? Unclear what part of the drag and drop functionality you mean
Where would you be dragging from
yeah true
so i would have a class definintion and a scriptable object with a reference to the class type?
I'm not sure I follow that sentence
but where would I put this? in GenerateGrid() where the grid is being created or in Update()?
public class sampleclass { // definition } -
public class scriptablesampleclass : ScriptableObject { public Type = typeof(sampleclass) }
@leaden ice
Right at the spot where your code is about to access it incorrectly
Wherever the exception is being thrown
No...
Just one type
The ScriptableObject
Ok I think I'm just now understanding your original question
wouldnt the state then be global and i couldnt have multiple instances?
You want to serialize a C# type
yeah
Does it need to work at runtime?
yeah
final design not known for sure but say id like to be able to instantiate a number of different classes on awake/ start/ in response to input events and the classes that will be instantiated can be changed through the inspector instead of modifying code
The simplest approach is to just use prefabs
But you could also do this through Editor scripting
I.E. search your assembly for Types that satisfy some criteria and populate a drop-down with them
Then serialize the chosen fully qualified type name as a string
if i were to do prefabs this would just be empty game objects with the class attached as a monobehaviour?
Sure something like that
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
EditorSceneManager.SaveOpenScenes();
Anyone have a clue why this takes very long? When I manually save, the save takes around 8-10minutes. It's a very large scene. When I do it with this function, it takes 1h30?
for some reason, setting the velocity of a gameObject to 0 doesn't stop it. does anyone else have this problem?
(btw, no script directly changes its coordinates)
Hi guys, I have a question regarding the overall structure of a script.
In my games I have coins that, when close to the player, they gets pushed towards him. Once its close enough, the coin will disappear and the player gets a point.
The problem is that I feel like the script is mixing two things: pushing a gameobject towards a player, and assigning a point to their score. I've looked around, read about delegates but I'm not sure if that's really the way to go.
Could you take a look and tell me what you would do?
My problem lies in line 24
Personally, I don't think it poses much of an issue. It's not the best practice to put everything into 1 script, but in this case, it's only 1 line of code. And it helps to have only 1 script to know where to look if you have a problem.
If the coin isn't a prefab, I'd say ditch GetComponent and use a serializeField to drag the ScoreManager into the script(in the unity editor)
getComponent is expensive
It's not the worst structure. But I would probably inverse the logic. Keep an empty component on the coin just to identify it (better than a tag) and make your ScoreManager increase score itself. Also you can make a separate CoinAttractor that will push coins closer.
It's a 30 line script anyway. It's not really worth it to complicate it.
I would replace OnTriggerStay with a OverlapSphere for attraction and OnTriggerEnter for adding score
(im new btw, sorry if im incorrect)
Yes if it works it's fine, but we are discussing what can be done better
You really don't want to have a ScoreManager dependency in the Coin class. I think coins should be as independent as possible
why?
Thanks to the two of you :))
I'll keep your comments in mind regarding the GetComponent @boreal jewel and I'll go with the OverlapSphere + TriggerEnter. Thanks!!!
So you can spawn coins and place them wherever you want. Currently it is kinda independent because you have a tag check and GetComponent, if you were to switch it to SerializedField you will lose the ability to create new coins. Also a side note: if you do a tag check and a GetComponent after that, you can skip the tag check and just use TryGetComponent
If the levels not going to be generated anyway
he can just duplicate
GetComponent is not that expensive if done once in a while. Just don't do it in update and cache the reference
yes, but it's just another thing to keep track of
ur right
restart scene button works only once after applying dontdestroyonload()
works fine for other levels but not for level 1
Make sure you have script attached to gameobject in every scene, but I recommend Don'tDestroyOnLoad
Or unity has check to not load the same scene and that's what prevents it from restarting
when you reload the scene your button has a reference to another CameraMovement instance that I guess is destroyed. Make a separate component just for the restart method since it is basically static and don't mark it with DontDestroyOnLoad
ohh you're right, the script was attached to the camera which gets reset
do you mean like use a different name for the script?
Make a separate script just for Restart logic and attach it to the button directly, no need to have it in CameraMovement
yea I agree, its probably where all the problems stem from
thx alot for the help man 🙂
One question, would you put OverlapSphere in an Update function? I'm afraid that if I have 100 coins around the world, they will query several objects in each passing frame
Yes, I'll put in Update but not in the Coin class. Some other class should check for coins in range
Shouldn't you be washing cars?
You could get away with putting it in fixed update as well. Shouldnt really affect anything in this case unless you're moving at insane speeds
Ok thanks 🙂
I've ended up doing just that but adding a masking layer to the OverlapSphere which came in handy
i wanted to know if there is way to calculate the time it took to perfrm a jump
Sure. Record the time of the start of the jump and the end of the jump. Then subtract.
life if a log the time only when its in contact with ground
no but how do i record it>
i try to obfuscate my code with plugin on unity asset store and i have this error. How to fix this?
!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.
Can someone tell me how to share my code here? The !.code thing doesnt work for me (it probably works but I just dont know how to do it)
Thats why I said it does work I just dont know how to do it. Ive been here for like 30 mins trying to understand the instructions, but nothing works. Thatswhy im asking for help
I don't understand how these instructions are too complicated.
You go to https://gdl.space. You paste your code into it. You hit save. You copy the link.
oh ok, i was trying to inline it but my code probably is too long for that
Anyways, can anyone tell me whats wrong with my movement script? whenever i try to press play in the editor, the player automatically starts moving backwards without any input. all my troubleshooting has failed.
no. ill send a pic of the log in a sec
Do you have a controller connected to your computer?
(or even a controller not connected to your computer?)
Here’s the log:
wait i might have just foudn the problem
if this is it im going to feel so incredibly stupid but hol up
nope it wasnt the problem
anyways, i have a xbox controller and a steering wheel, neither of which are connected to my PC
Turn off Collapse so that it's clear what the most recent value is
also, please take screenshots instead of photographing your screen..
okay, so the vertical input looks like it's stuck
Hello!
Connect both and wiggle them around a bit. See if that resolves the "phantom input".
can i get help with something?
I've had problems where a disconnected xbox controller produces phantom sticki nputs
if you ask a question, maybe (:
Okay so basically I have URP I think its called the lighting thing and its going on the whole map but i want to add it to one singular item
the controller is a xbox controller so I cant connect that but I can connect the steering wheel. ill test it and see what happens
this is not a code question
you told me to ask 💀
show screenshots of what you're doing in #archived-lighting
because the server expects you to write complete messages
messed around with the steering wheel for a min, still have a input
Do you use input system or the old input stuff?
They use the old system with Input.GetAxis