#archived-code-general
1 messages · Page 434 of 1
yes but he doesn't have any?
Thanks for the response! I'll look into how coroutines work and try to find a solution like the one you suggested. your option B didn't make sense to me as I am relatively new, I don't see how I could store the info you're talking about in a bool. So I'll try option A for now. Again thanks for the response!
bool _isDragged;
public void OnBeginDrag (PointerEventData eventData) // Or any equivalent
{
_isDragged = true;
}
public void OnPointerUp(PointerEventData eventData)
{
_isDragged = false;
}
void Update ()
{
if (_isDragged)
{
// Do something that should be done only during dragging
}
}
Well don't mind if I just borrow that...! Thank you!
you have 3 different namespaces, 2 of them being used thats why they are not grayed out like Unity.VisualScripting
System.Numerics contains Vector2 and UnityEngine also has Vector2.
the computer has no idea which one you want
so I have to delete them?
Only the one you don't want to use
in this case you wouldn't want the one from System.Numerics, VisualScripting one can be deleted too cause thats not even being used, hence the grayed out text
ok thank
Anyone here knows how to make recording cameras? like content warning does? i know few APIs, but they're all paid, is there any free option?
@copper lodge I will also add, that Visual Studio automatically adds namespaces as used ones whenever you try to use something that could belong to this namespace. In this case, you used Vector2, and your code editor noticed that the namespace was missing, so it added one. While this feature is convenient in most of cases, sometimes it adds the wrong namespace, if there is more than one potential candidates. This feature probably can be turned off in settings.
iirc it adds the first alphabetical one right ?
No clue, I haven't investigated it.
ok thank you very much everyone I'm new and French too so I had trouble but thank you very much, is it good like that?
Carrying objects in Unity first person. Help please!
Hey I'm using Unity 6 and it seems like Cinemachine has changed up a lot of its scripts.
How do I get a simple follow/look at where I can specify a tracking distance
thanks
this is my current speed control and moveplayer code, i want to make it so that instead of slowing the player while grounded if they are over the movement speed, it just prevents them from accelerating with movement keys
how would i do that
that'll mean you have an inconsistent max speed
yes
i want the player to reach the max speed i set if they hold w, but if they recieve external force, they wont instantly drop to the max speed
i mean even with just holding w you can get inconsistent max speeds
how inconsistent
hmm not sure
the way it currently is, the instant you touch the ground, it drops your speed, i want basically anything besides that
actually MovePlayer is called from FixedUpdate, right?
it should, given the AddForce with Force
yes
since the deltaTime is consistent i think that wouldn't be too much of an issue
originally i was thinking about framerate affecting the acceleration step size
but that won't be an issue
there will still be some inconsistency with different friction or drag perhaps... that could end up jerky, but ig you'll have to test for that
but i dont know how to put it in
then do that
you can't undo an action
well i mean you can with AddForce but you shouldn't, for the sake of your future self
so you have to choose whether or not to do it
i just want it to prevent rb.AddForce from doing anything
you can't
but you can choose to not AddForce at all
invert your condition; only if your speed is under the cap, then do addforce
im very new to c# so idk how i would format
do you not understand conditionals?
i do
you're already using them in your code
you can translate this basically word for word to code
this is code i made from a tutorial, so i only understand it a little bit, and im just tweaking it to my liking now
if (speed < cap) addforce(x);, put it in a block if you want, substitute in the proper values and variables
you should seek to fully understand the structure and logic of the tutorial code instead of just blindly copy and pasting
there are beginner resources linked in #💻┃code-beginner
if you have further questions, consider asking there
ok it needs some tweaking still but its a litle closer to what i want
Hi all, I'm trying to set up a parallax script with infinite scrolling but I'm getting an error that "length" does not exist in the current context
I'm using Unity 6 (6000.0.40f1)
get your !IDE configured. after that, don't attempt to use variables that don't exist 😉
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
what is a typical way people make a wraparound map? so on a plane I start at A, go to the left side to end up at B, then go up to the top and end up at C.
i dont think it would work if I just teleport the position from A to B, B to C, becuase I have a rigidbody character, it doesnt really work all that well if I did an instant position change over a distance
Can't you use RB.MovePosition?
maybe, but I imagine there could be issues if i was to do it with teleporting. like a trail renderer would end up creating a massive streak across the map, and enemy targetting would head towards the left edge, then theyd do a 180 to head to the right edge
MovePosition does interpolation so it won't work here
if it makes it any easier, I'm probably only going to let you move to A-B there isnt going to be B-C for the top wrap around
Have you already tried doing teleporting with position change or are you just anticipating issues?
I'd used teleporting for the player before when I wanted to set the spawn point, hadnt realised you could do MovePosition, so I had a pretty hacky thing of setting its body to kinematic, teleport, then lateupdate set it back to non kinematic
For the enemy AI, you're just going to have to hard code that such that enemies can also wrap around
It's going to look jank otherwise
thing is if its just wrapping around from left to right, that means the map is just a cylinder
I dont know if its really possible, but if I could make it so driving in one direction basically is like an infinite series of squares, youd end up always returning to 0,0
unfortunately my vehicle controller doesnt really work in 3D, its only really designed for a 2D surface
it is something I'd thought of doing
ill do some research and see if anyone has solved a similar thing to this
Is there an accurate readout for the tension a joint is under? Right now I'm just checking currentForce and I've tried it with torque and can't see another reasonable field for it. Currently this is logging as 0 so I assume this is force as in AddForce and not close to what I want 😅
while (jointEffect.configurableJoint.currentForce.magnitude < 0.5f)
{
Debug.Log($"Waiting: {jointEffect.configurableJoint.currentForce.magnitude}");
yield return new WaitForEndOfFrame();
}```
I have a tech tree in my game. well, at the moment more of a group of techs with a few dependencies. It's all working on the back end, unlocking things changing stats etc.
I need to make a front end for it though. I have a canvas where I intend to do this.... but not really sure how to handle a techtree that exists as a set of scriptable objects. totally open to using an existing solution rather than reinventing the wheel
it wont log at full precision (i think) so debug (use a debugger) or format the float to see more info
I'll try to 6 decimal places maybe, It does seem to be under a lot of tension in game which is why I'm a little confused
Well, that's not great
is it bigger than float.Epsilon?
Nope
then is zero for real 👍
Any ideas as to how I can fix it? I know it's too low to work with already haha
I'll take that as a no, then. I'll just use rigidbody.Velocity 🙃
Show your joint settings, what kinda limits it has etc?
Like is there anything that should make it use force
Velocity actually works perfectly for what I need, so there likely isn't a need to fix the currentForce issue, thank you for offering though 😃
wraparound in both directions is a torus fyi. i don't think that helps you though
Is it true that referencing Transform instead of GameObject is cheaper? And should i use it instead?
I was always using GameObject
And should i use it instead?
not for this reason, no. use what makes sense
computers are fast
a little indirection won't have any effect
don't worry about optimization until it becomes a problem
in general, you usually shouldn't reference GameObject since it's not super useful on its own. use a type corresponding to what you do with said object
if you follow the transform, referencing the Transform directly would make more sense
if it's an enemy and you want to interact with a script, reference that script
etc
Okay, Thank you!
I usually use reference to GameObject if I want to use GameObject's methods, e.g., SetActive, and I usually use reference to transform when I want to do operations on transform. Whatever makes coding more convenient. Sometimes I even store references to both if I need to access them many times.
Its just that, im working with some source, and it references prefabs as Transform...
Thanks for info!
Can someone help me with carrying game objects in first person? I have a Thread created with all the information. Thank you so much!
I think the main downside of such approach is that you won't see any prefabs in your Asset list (it's because for sake of performance Unity doesn't open them all to scan their components). Drag-and-drop works fine though. In the past I was sometimes losing references to prefab components, and I'm not sure what could cause it. I don't have such issue lately, so it could be some bug in older version of Unity. I often add references to my own components, making it easier to initialize things without using GetComponent, and it also prevents me from using a prefab that doesn't have such component.
Hmm, ill think about it, thanks again!
using UnityEngine;
using TMPro;
public class Movement : MonoBehaviour
{
public Rigidbody rb;
public float Walkforce;
public float Climbforce;
public float Descendforce;
public TMP_Text TimerText;
public TMP_Text SpeedText;
private float playerSpeed;
private bool isTimerRunning = false;
private float TimerTime = 0.00f;
void FixedUpdate() {
if (Input.GetKey("a")) {
rb.AddForce(-Walkforce, 0, 0);
isTimerRunning = true;
}
if (Input.GetKey("d")) {
rb.AddForce(Walkforce, 0, 0);
isTimerRunning = true;
}
if (Input.GetKey("w")) {
rb.AddForce(0, Climbforce, 0);
isTimerRunning = true;
}
if (Input.GetKey("s")) {
rb.AddForce(0, -Descendforce, 0);
isTimerRunning = true;
}
if (Input.GetKey("m")) {
isTimerRunning = false;
TimerTime = 0.00f;
}
if (isTimerRunning == true) {
TimerTime += Time.fixedDeltaTime;
}
playerSpeed = Mathf.Abs(rb.linearVelocity.z);
Debug.Log(playerSpeed);
TimerText.text = "Time - " + TimerTime.ToString("F2");
SpeedText.text = "Speed - " + playerSpeed.ToString("F2");
}
}
guys why is playerSpeed 0 when the cube is moving?
all the script works so it's not an issue, but playerSpeed is 0, thus SpeedText is 0, please help
Answered you in #💻┃code-beginner , don't crosspost
Since I got buried again: can someone please help me with carrying objects in first person?
I have a very detailed explanation on a thread. I linked my code properly as the rules advise. It’s formatted nicely. Please I need some help!
https://discord.com/channels/489222168727519232/1353059934920642582 here i think? I didnt know that sorry! will do that going forward!
I am trying to manually trigger OnDrop from another script, but it's not working. I am wondering what I am doing wrong.
I am trying to trigger OnDrop from the OnPointerUp function in OnEmotionInvClick. This is to trigger the OnDrop function in EmotionDropHandler.
EmotionDropHandler script: https://paste.mod.gg/ngqviaqxnxiz/1
OnEmotionInvClick script: https://paste.mod.gg/ngqviaqxnxiz/0
I am getting the error:
"NullReferenceException: Object reference not set to an instance of an object
EmotionDropHandler.OnDrop (UnityEngine.EventSystems.PointerEventData eventData) (at Assets/Scripts/EmotionDropHandler.cs:22)"
I am not sure if I've used the syntax correctly, and there is little to no documentation on triggering OnDrop from another function.
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
well did you check if canvas was null?
its not really related to your main question
No and I don't think I need to, as the canvas always is there and does not change
btw doing get components all the time is not good, get once and keep a ref and work with the script type instead of GameObject
clearly not if its throwing a null ref exception 😐
MyClass c = null;
c.DoThing(); //NullReferenceException will be thrown!
(i am going off the line numbers in the pasted code btw)
It's not throwing a null ref exception to finding the canvas, the error is in the EmotionDropHandler script. The error is relating to this line of code:
Debug.Log("Drop info| Dropping on: " + gameObject.name + " | Object dragged: " + eventData.pointerDrag.name);
Also I will not completely rewrite my scripts to remove all the GetComponents as the project is very nearly finished, and I want to move on haha.
ah you miss labelled the links
then either gameObject is null, eventData is null or eventData.pointerDrag. Im guessing eventData.pointerDrag.
Huh, the link itself is correct but when I click on it, I am taken to the other script for some reason.
You're right, it's the eventData.pointerDrag that is null, I don't get why that is the case though.
i guess we can presume the drag ended so this is no longer set
It does not trigger the drag at all the first time it's instantiated, as it is instantiated when the player is holding the mouse down. I'd need to unclick and then click and drag it again for it to trigger, which is what I am trying to work around
Oh right i remember. Perhaps it would be better if you you have containers to hold these objects so the use can drag one out. You can then create a new one in the container when the drag begins.
may be simpler vs trying to transfer the input to another new object as it seems its not exposed for us to modify easily on an event system
The container is to make sure layout is not messed up by this
Could be a good idea, but I think I'd need to rewrite some scripts. I think I'll just try to find a way to do a raycast to check for objects underneath
how would i go about making this code work where isnted of using raycasting to find the grapple point i throw an object that attaches to a surface
using UnityEngine;
public class puzzle : MonoBehaviour
{
[SerializeField] private float grapplelength;
[SerializeField] private LayerMask grapplelayer;
private Vector3 grapplePoint;
private DistanceJoint2D joint;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
joint = gameObject.GetComponent<DistanceJoint2D>();
joint.enabled = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast
(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
direction: Vector2.zero,
distance:Mathf.Infinity,
layerMask: grapplelayer
);
if (hit.collider != null)
{
grapplePoint = hit.point;
grapplePoint.z = 0;
joint.connectedAnchor = grapplePoint;
joint.enabled = true;
joint.distance = grapplelength;
}
if (Input.GetMouseButtonUp(0))
{
joint.enabled = false;
}
}
}
} ```
thats gonna suck and your scripts need improvement anyway by my standards so id re do it in a better way
Like I said, this would be the last line of code and I am not interested in rewriting it when I have spent such a long time making it in the first place. Took me many, many hours total. Might be a bad practice but I need to finish it
Sometimes we have to accept that something isnt written well or no longer meets requirements. Don't cling to it but use it as a learning experience to inform what you make next.
I often realise I need to refactor something but don't have the time but sometimes it becomes essential to refactor to resolve a critical issue/flaw
I appreciate your help and your suggestion, I realize it isn't written well, but getting it to this working state was a marvel for me in the first place. If I try to optimize it (which isn't necessary performance-wise) without knowing what exactly the problem s, I'll spend much more time
So thank you but I'm going to google raycasting now
and I'll cast that ray
I think you can only use the graphic raycaster to do this: https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.BaseRaycaster.Raycast.html
up to you what you do and if its just for you/ some student assignment then if it works its probably good 😆
It was just an idea I had on a whim to make a game I could actually complete this time around, (Just a prototype/10 min game) I've learned a lot but it was a bit above my skill level. So I'll be using that ray cast as a duct tape, and thanks for the link!
I think the problem comes from the code? but I can no longer launch the game
you need to get vs code configured 👇 !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
what is even the point of that screenshot if its not even showing the error on that line. But yeah you need configure IDE first
here's another link with the same instructions but also some extra troubleshooting steps https://unity.huh.how/ide-configuration/visual-studio-code
Hey there, does Unity have some sort of super sneaky tag that names exposed to editor array elements along an enum?
so let's say I have an enum that goes like {Red, Green, Blue} and then create a serialized Color[] array, and I want the element 0 to automatically be called "Red" instead of "Element 0"
is there a smart and lazy way for that or do I need to create a struct
well, found a community-made solution for that
why not use a serialized dict for that
more long time effort for the same effect 🤷
I'm trying to lazy-max the case
two clicks instead of one you get me
well serialized dict would give more flexibility as to which members to include
that is not needed
but if that's not applicable to your situation then 👍
what I'm making is a way to serialize game's global color palette
all colors will always be mandatory
should it even be an enum+array then?
why not a struct
that way you require the ones at the end as well
the enum is there for naming which general concept this color represents
a struct was my first idea, but that's again two clicks per element
you can do that with a struct too, with the member names
it isn't though?
oh you're thinking of an array of structs?
ah, you mean a struct like that
yeah we just missed each other for a moment 😆
I now get it
might think about that
[Serializable]
struct Palette {
public Color32 red, green, blue;
}

an array would be 2 clicks per element
this is probably a little better
1 to add an element, 1 to set the value
well damn, you out-lazied my idea, well done
Any insights on this? the thread is linked here: https://discord.com/channels/489222168727519232/1353059934920642582 all the information is there:) thank you in advance!
I've got a question about scriptable objects, how can I use an enum inside of a scpriptable object
with uitk it's very easy by parenting multiple DropdownFields in a single visualElement to mimic the array order
var dropdown = new DropdownField();
dropdown.choices = Enum.GetNames(typeof(MyEnumT)).ToList();
OR even better, just use ListView
they aren't trying to choose an enum value
just to show?
they're applying bindings/entries/values corresponding to each member
oh no idea then
bump
You should be able to make a public variable for it the same way as any class, as long as the enum type is also public - how are you currently trying to use a enum in a ScriptableObject that is not working for you? Are you getting any errors?
Enums just don't appear in the inspector, and neither unity or visual studio give an error
`using System.Collections.Specialized;
using UnityEngine;
[CreateAssetMenu(menuName = "PhantomDev/New Attack")]
public class Attack_SO : ScriptableObject
{
[Header("Attack Descriptors")]
public string attackName = "{Name goes here}";
[TextArea]
public string description = "This {enter type here} {was/is/could be/may be/etc} {backstory} \n {does this and that}";
[Header("Attack Stats")]
public int damage = 7;
public enum attackType { Sword, Bludgeon, Magic }
public enum attackElement { none, Water, Fire, Earth, Wind, PureMagic }
public bool bleed = false;
public int amountOfUses = -1;
}`
You defined the enum type but never made an actual variable
There's no difference between an enum and any other type. The type definition is different from a variable of that type
// Defining the enum type
public enum MyEnum { A, B, C }
// Making a variable
public MyEnum myVariable;```
OMG thanks a LOT
currently getting an error that my class doesnt implement inherited abstract members, when it very clearly does
any chance at seeing the base class too?~
ye one sec
also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
how do listeners for events "know" when the event is fired? do they check every frame? does the event itself go looking for listeners?
like c# events or UnityEvents?
using UnityEngine;
using System.Collections;
public abstract class ItemClass : ScriptableObject
{
[Header("Item")] //data shared across every item
public string itemName;
public Sprite itemIcon;
public abstract ItemClass GetItem();
public abstract WearableClass GetWearable();
public abstract ToolClass GetTool();
public abstract MaterialClass GetMaterial();
}
C# but im curious about UnityEvents too, but havent used those yet
thats the itemClass script
well they're really all just delegates so they have a direct reference to the method(s) they are invoking. there's no "checking every frame" or anything like that. you invoke the delegate and every method subscribe to that delegate is then invoked by it
UnityEvents are a bit different because of how they are serialized, but it's still just a wrapper for a delegate
i have just bar for bar copied and pasted the two classes and its working fine for me. Try removing the methods and use the IDEs "Implement abstracted method" tool tip?
(The mystery behind events is that functions themselves can actually be handled as a stored data type, so events basically have a list of functions they fire off that you add and remove from)
so whats the reason you have to subscribe/unsubscribe? you shouldnt be able to call a method on a disabled object so i dont get that
You can call stuff on disabled objects
you have to subscribe to an event so that the event will invoke the subscribed method. if you don't do that how could it possibly know what method to invoke?
sorry i meant unsubscribe specifically
with OnEnable/OnDisable
People assuming disabled objects can’t use functions is usually a misunderstanding due to them not longer receiving update calls
actually youre right
a c# event such as event Action blah; can be subbed to or unsubbed at any time and invoked at any time.
well c# doesn't have the concept of enabled or destroyed, those are both unity-specific concepts that don't really mean much for the code you write except for some specific methods and properties you might access/use.
if you don't unsubscribe an event then that method will still be invoked because the delegate still has a reference to it. this can lead to memory not being correctly released (the object cannot be GCd if something that isn't also being GCd still references it), and it can also lead to exceptions (like MissingReferenceExceptions which happen when you try to use a destroyed object)
ah that makes sense
learning programming with unity makes it all kinda jumble up together
(Aka: people do that because they should, not because it’s a built in requirement of events)
when you don't use Unity MB methods, you can use methods to cleanup, such as implementing the IDisposable and call it on the Dispose method
There’s a lot of programming stuff that becomes a lot easier to understand when you figure out what people have to do and what people should be doing
this is why i personally think it is best to learn the language and how it works before diving into unity
so if C# doesnt have "destroy" or "disable", how do you handle unsubscribing outside of unity? would you do that before setting the object to null?
C# has destroying objects as a feature but Unity’s destroy does a lot more for a bunch of various reasons
usually yeah whatever would set it to “null” would also contain stuff to correctly handle its destruction which might include unsubscribing from stuff
.net framework /c# does have such
oh thats what that meant
as it says its more for manual release of unmanaged stuff
unsubscribing here is unnecessary ?
I always used that on blazor when component gets disposed
i think using Dispose() to then unsub is misleading
Also it’s not fully an event but you can kinda use the Update() example of how events kinda work in practice, where unity just does an Update() every interval and alive, enabled objects listen to that and receive that call until they don’t need to. Unity doesn’t need to know what is listening to the event it just gives it out to anyone interested in listening
up to whatever you are doing to decide when you want to unsub from events
yeah that part i get, i was just curious how it works behind the scenes
i heard from one of my colleagues that there is some overhead to having an event subscribed
is this false then
Yes, go for it. Although some people think IDisposable is implemented only for unmanaged resources, this is not the case - unmanaged resources just happens to be the biggest win, and most obvious reason to implement it. I think its acquired this idea because people couldn't think of any other reason to use it. Its not like a finaliser which is a performance problem and not easy for the GC to handle well.
https://stackoverflow.com/questions/452281/using-idisposable-to-unsubscribe-events
no clue if there is any truth to that though
guess it doesnt matter what the function is called 🤷♂️
as long as its cleaned up ye?
👍
I was always under the impression it was good practice
delegates are immutable so each time you subscribe or unsubscribe to one it creates a new instance. that's really the only "overhead"
and if you don't unsubscribe to an event then the subscribed object can not be GC'd (like i mentioned previously) so even if other objects have stopped referencing it, it will still hang around in memory until that delegate is also GC'd
You can also have a boolean flag that indicates if it's cleaned up, and throw an error/warning in the destructor if it wasn't properly cleaned up
so rather than an "every-frame" overhead, its just when subscribing (creating an instance) and unsubscribing (removing an instance)?
ah i see
okay that makes sense, thank you for the explanation
it creates garbage when you sub/unsub. but unless you're doing an absolute fuckload of subscribing and unsubscribing from delegates it won't really make much difference in the long run
I do wonder what the overhead is of unity "messages" as its doing a native -> managed call (somewhat removed in il2cpp)
https://discord.com/channels/489222168727519232/1353059934920642582 why is it behaving so differently for me? I'm using the exact same code as he provided and we both confirmed its set up correctly. I never expected this to be so challenging:( Alls im doing is basically making a walking simulator. Nothing crazy.
i got a question, if i got an object singleton and i subscribe to an event inside Start() i wont need to disable this event with OnDisable(), right? since the object will never be destroyed and Start() will only subscribe to the event once, avoiding memory leaks
make your own system from scratch, they usually work better than copying
this way if something goes wrong you can easily know why
I understand that. but im trying to zero in on the problem. making my own wont help when even a 100% working script wont work. that proves their is some other conflict.
it's still best practice to unsubscribe just in case you ever decide to change the lifetime of that event. But you can unsub in OnDestroy instead of OnDisable so you only sub/unsub a single time
yea thats beautiful then
so could it be that im using the New input system for nav and look, while this script uses the old system? They said it shouldn't matter. and its not like it doesnt work, it does. but the physics just tweaks out and gets worse over time. makes no sense at all. but I'm literally completly lost here. at this point Im willing to start over to day 1 and learn eveything again. but everything is 9+ years old and teaches you to put everything in the update method. setting you up for failure. so idk what to do anymore. @rigid island
I have no idea what the problem is, there is too much to catchup to tbh lol
What's wrong with putting things in Update ? what is currently happening vs what you expect
I use Update for my pickup object scripts all the time
im told that you should put as little as possible in update for prefomance sake. i mean if its fine its fine, but not good to just go ahead and do that for everything. like checking inputs for every frame for example. for them. they pick it up. it follows the camera. and it drops when they let go. for me: almost the exact same thing, except it bounces up and down. I put it down again, pick it up again, its bouncing more aggressively. progressively getting worse the more i interact with it. as if values are changing on the fly. despite working perfectly for them. my debugs work exacly as expected too. so the script should be working in order properly.
okay show a video most recent behavior in your thread Ill take a look
also depends on too many factors to determine what is ok in Update or not
its more about what computations are happening x how many instances so yeah in some cases but not here
the code youve shown shouldnt have this error, do you get a compile error in unity for this?
also the code is questionable, ItemClass has a reference to WearableClass which is a derived class. This probably shouldnt be done
oh sorry, didnt see you mention the thread
send it in the thread so we dont flood
nvm, found the issue, apparently i had a duplicate of the itemclass file elsewhere
Interesting, I was thinking maybe you had a duplicate of wearable class. Either way I still think you should reconsider what you're doing with the inheritance here. It doesnt really make sense for a base class to know anything about the derived classes
i suppose not, im just following a tutorial someone else in the server reccomended rn
If it's just for learning purposes then carry on. Most tutorials are quite bad for a real implementation
They quickly break when you want to extend its functionality. Like in your case if you have something else derived from ItemClass, that isnt WearableClass, itll have to return null for that one method everytime.
Same like how you're doing for the other methods in WearableClass, which I now realize you likely have more things deriving from ItemClass
👍
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeaCrate : MonoBehaviour
{
public LevelManager levelManager;
private GameObject player;
private Tasks playerTask;
private void Start()
{
while (playerTask == null)
{
player = levelManager.instantiatedPlayer;
playerTask = player.GetComponent<Tasks>();
Debug.Log(playerTask.ToString());
}
Debug.Log(playerTask.ToString());
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 4)
{
Destroy(this.gameObject);
playerTask.CompleteTaskAction(0);
}
}
}
Hello, on the code above, I keep getting NullReferenceError for the playerTasks, but none of the debug statements are working?
You don't have a reference to use Tasks maybe ?
doesnt playerTask = player.GetComponent<Tasks>(); work?
there is a tasks component on the player
Sometimes it can bug out in runtime. Usually I do that in Awake function so it grabs it before the game starts
If u need it during runtime then you need to hardline the reference before its used in code
still doesnt work after changing start to awake...
But is it a character that spawn in to the level ?
It is instantiated in the LevelManager
Which line? That while loop looks dangerous. The only thing stopping it from being an infinite loop is the null reference exception I suppose.
An if statement would be more appropriate, not while
Right so as i gathered with your script you instantiate the character then when it starts your saying while playerTask is null you have to grab its own reference and get its own component ?
yes
in playerTask.CompleteTaskAction(0);
i added the while loop to debug, but somehow the debug statements are not printing
are you certain there are no other errors before that one?
Have you tried just serializefield the Tasks and in the prefab or wherever you have your character and dragging it on so its hard coded ? then getting your own reference you don't really need to if the script is on the player. If your trying to say player equals the instantiated player its going to be like who ?.
this is my current log, the watershader errors doesnt seem to affect anything
the script is not on the player?
Can it be ?
Does it need to be elsewhere ?
well i have it on a box that when thrown in water dissapears and increments the current task, which is attached to player
read your previous error. that is what has caused your issue.
yes, the nullreference
im not sure why though
it is literally as it says 😐
It cant find the player
no, the one before the NullReferenceException
the one on the teacrate script, ignore the water shader errors for now
you know how to read, right?
Yes
then read the third log in your console in the screenshot you posted.
Wait oooooohhh, sorry everyone
yay
I have instantiatedPlayer = Instantiate(player); though...
clearly its not happening soon enough
It can't find the player
show the class that line exists in
Pretty sure that would throw a different error
"The object you are trying to instantiate is null" or whatever
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
public GameObject player;
public static LevelManager Instance;
public GameObject instantiatedPlayer;
private Tasks playerTask;
// Start is called before the first frame update
private void Awake()
{
Instance = this;
}
void Start()
{
playerTask = player.GetComponent<Tasks>();
SetObjective();
}
void SetObjective()
{
instantiatedPlayer = Instantiate(player);
Scene scene = SceneManager.GetActiveScene();
switch (scene.name)
{
case "Intro":
break;
case "Boston Tea Party":
Debug.Log("Current level is boston tea party");
playerTask.AddTask("Lance des boites dans la mer", 3);
break;
}
}
// Update is called once per frame
void Update()
{
}
}
True but its still true with what I said. It would have to be the level manager with out a reference.
there is no guarantee that this object's Start method runs before another object's Start method. spawn the player in Awake instead of Start
plz dont confuse them (batty251)
So don't help ? okay. I remeber why I don't post here..
or (and this is what i would do, but would probably be a bit more confusing for you at this stage) you could instead have the other object subscribe to an event that your LevelManager invokes when it spawns the player (that event could even pass a reference to the player object)
no offense, but your help wasn't actually helping them in any way and was really just serving to further confuse them
it was a bit confusing how you said it hence someone else responding to say otherwise
so you are saying levelmanager calls a function of teacrate to pass on the instantiated player?
that is an option, yes. the easier option for you would be to simply merge the Start method of LevelManager into Awake.
Get the reference to LevelManager then You get a reference to the player. All i said was "It can't find the player". Its all one line so no its not false but its alright I am just confusing
We understand the issue but its most helpful when we describe as clearly as we can what the problem is. nothing to worry about anymore though
I see, ill try it
Good so you can deal with or help anyone else that comes asking then ? cool beans enjoy
what i say doesnt have to stop you im just a rando user
you do you, we are here by choice to help when we want
Thank you everyone, i figured it out, it works now!
Hey guys, I’m having an issue with a dictionary in Unity. I’m storing keys and values, and when I print all the elements in the dictionary, everything looks correct—all the keys and values are there. However, when I try to search for a specific key, it doesn’t find the last key in the dictionary.
For example:
If I add a new key, the previous key that wasn’t being found suddenly works, but now the new key I just added isn’t found.
If I add an empty element at the end, it works, but I don’t want to use this as a solution because it feels like a workaround.
Something seems wrong, and I’m not sure what’s causing this behavior. Any ideas?
you should show !code, what you're describing doesnt really make sense and just isnt how dictionaries work
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
also "add an empty element at the end", dictionaries dont have an end, they aren't ordered
A tool for sharing your source code with the world!
I see but it's the last element in my CSV file
so you know, a real csv parser needs to handle " correctly but its your data i presume so okay for now
i see. one thing you should really do is just use an existing library to read from the file.
im not really sure what lines you're referring to though based on your description above
also i cant tell if theres a difference, since idk the language, but those first 2 columns in your file looks like the same character
every thing is work but when i try to dectionary.ContainsKey(key) to get the value the last key i add in my csv value not founding
then you havent added that key into the dictionary simply
no it's different it's work when i add empty value in the csv
Does that last value appear in your debug logs when you parse the file?
this would really be solved if you just used an existing csv parser which handles everything properly. you do have debugs in your method though seemingly printing out everything, cant you see in the console if everything appears?
I am curious why in the printer I see the value but when I search about the key it's give me not founding
yes
Try printing out all the values at the end of the parse csv method
you can go through it with a foreach, then access the key and value
Then add a breakpoint with a condition to break on the last element and step through the code to see if the key-value is added to the dictionary
ok I will try thank you so much
thank you @lean sail and @steady bobcat
yes use a debugger to verify each item is added correctly
Unity UI: Why does viewport.rect.width change so drastically between resolutions?
hellow, im new in here
i made a game its a simple proyect, and i made a build of the proyect but when i run the .exe file, its start with the unity logo and then it stays loading in a grey screen
pretty sure that's the splash screen and not actually code related, unless i'm wrong. show a video
What's supposed to happen then? Did you not add that loading with gray screen?
i think is something like that either but i dont know how to solve it
nop, the game has no ui
I don't see any loading screen. What's point of the video if it doesn't show the issue?😅
Guys so i want to learn more about Unity's C# and i really dont want to waste 5h doing tutorials and in the end have no idea about making stuff on my own
c# is its own language, unity uses c#. you can learn it outside of unity
but simply, if you dont want to learn then 🤷♂️ what do you expect lol
and you'll waste way more than 5 hours
Sorry, you know what is happening ?
Reasonable, i kinda just wanted a quick way out of grinding this out. but thanks for giving me a reality check
Did you assign your scene in the build settings?
I don't see any loading screen. Just an empty screen.
good one 👍
I would suggest starting with w3schools C# course, get some practice on that site with the various topics of the language, then maybe move into Unity tutorials but try to avoid the "how to make x" type of tutorials, as they often skip a lot of important steps for beginners - a lot of "having an idea of what your doing" will come from... Actually doing, making many projects, trying things out, and practicing critical thinking skills as a programmer, and a lot of "avoiding hours on tutorials" as a means of progress is understanding how to break down your own problems into something you can code with what you understand about the language and engine and using resources like the docs, stack overflow, etc - its take a long time, but so will making any kind of game, especially if you plan to release that game one day
Alright great start, can you send me a link to that course?
yes
ill show you a ss
Sure, if you google "w3schools c#" you should be able to find it, I find that google works really well with finding resources by searching mostly with keywords
Okay. Try connecting the console to the build to see if you have any errors.
damn yall like to make mf's stupid, i like it though
much love to you
I dont think there are any stupid questions, just curiosity, programming is hard and it took a while for even me to realize google works better with keywords than full on questions or sentences - but as long as it helps in the end, then im glad I could help 🙂
which one is more expensive?
texture cast into texture2d
texture2d cast into texture
sprite.create using texture
Sprite creation probably.
btw this is a quite frequent execution
Casts are relatively lightweight
the thing is, we have two sets of textures before , because we have a set of poker cards needed to display in 2D and 3D, so we have a set of texture and texture2D
and someone decided to take one set away, we then take away the texture2D , only leaving texture
because we wanna reduce the app size
the problem is, if i only have texture, i will need texture2D for sprites
What is the actual type of the object that you are referencing with the Texture type?
Because Texture2D inherits from Texture
Can't you just use Texture2D type reference instead of Texture?
mainly two kinds
- texture = texture (this is fine)
- image.sprite = texture (this has problem)
but texture2D can be used on 3D objects?
im fine to have t2D or texture
but there can only be one
Yes, Texture2D is used for 3D
nice ty
texture2d is ideally used for 3d objects
There are also 3D textures, that's why it's called Texture2D
very rare you need just texture
i honestly didnt go too deep into this tho, because what i did before was solely prepare texture for 3D objects , texture2D for UI/2D objects
i never cross used them before
like using t2D on 3D objects lol
yeah as Osmal said, Texture2D is called that because it's a 2D Texture, not because it's meant for 2D stuff
i understand the confusion when unity has function names and components ending with 2D though
yeah they were so consistent on components when its for 2D projects lol
u know, collider2D/collider
yee
Thank you 😊
ok, for 3D poker cards, we gonna use texture2D as it is
for 2D poker cards, we will remove all image components and use rawimage, something like this
RawImage img = null;
img.texture = GameManager.Instance.cardTexs.GetCard("S0");```
where getcard will return a texture2D
I don't think you can even create an object of Texture type. It's sort of an abstraction for different texture types.
BackSideCard.GetComponent<MeshRenderer>().material.mainTexture = backSidemat.mainTexture as Texture2D;```
yeah the project is quite messy
we will interact with material in runtime and change the properties inside
this is how we deal with 3D objects
Materials usually have texture2d assigned. It could be referenced by the base class, but it doesn't change the instance type.
In my Gadget class, which extends the Item class, of which a List is stored in the Inventory singleton, I have an enum for its type as well as a public field of that same enum. Is there a better way to disambiguate their identifiers other than "Type" and "GadgetType?"
public class Gadget : Item
{
public enum Type { TurretDrone, StimDrone, ForceField };
public enum State { Waiting, Charging, Ready, Active };
public string GadgetName;
public Color GadgetNameColor;
public Type GadgetType;
private State _gadgetState;
...
}
Is this even a problem?
What's the actual point of either the enum or the type then
What's normally the point of enums, if not this? I could have the type be a string, or event an int, but I want to be able to pass an enum into the constructor so that I can't pass an invalid string and I know exactly which gadget is which from the IDE.
Why don't you just pass the Type is then in the constructor?
Enums are nice because they can cut down the amount of types your project needs
For example you may have a single Gadget type with multiple different variations where these enums define each one of them, or if say you wanted to create a type of Gadget1, Gadget2, ect. then you would instead have more types than enums
Idk what this means
Sorry glanced over it on my phone. Thought you were storing these objects as Type, but seems you named your enum Type instead.
Not entirely sure of the question therefore. Is this just a naming convention issue?
Yes
public enum GadgetType{ TurretDrone, StimDrone, ForceField };
public class Gadget : Item
{
public GadgetType GadgetType;
}```
this is what I'd do
It lives in the namespace (or global otherwise)
If you want better scalability, use ScriptableObjects in this role. That way you can create dozens of new types without opening code editor. You will also be able to create some type-specific code for each ScriptableObject's script.
Enums on the other hand are great for fixed number of types. It's also easy to find all references of particular type. The downside is, that there is no separate script for each enum, meaning that developer who wants type-specific code will have to insert it into some script, potentially making a long script file.
There might be a bug from version 6000.0.30f1+. I have a container VisualElement in which I add toggle elements and I "refresh" when I click a button. The first time when it initializes it's fine, the values change when the toggles are clicked, the second time and onwards breaks them - it makes them unable to change their value when they are clicked.
I do clear the parent element every time I "refresh" and I also create new Toggles based on dynamic values and add them to it. I also register a callback for value changed on each (new) toggle which after the second time it "refreshes" never gets called, but the ClickedEvent Callback does get called on them.
The same logic works with no issues in version 6000.0.11f1
This is a code channel (the name gives it away!). Unless your question is code related (it doesn't look liek it), delete it and ask in #🏃┃animation ... if it is code related, show the code
sorry
wat
how would i go about fireing a raycast in the direction of my mouse compered to the player and getting the postion of the first object it comes into contact with
and is there a way of detecting what object the raycast hit
Use Camera.ScreenPointToRay to create the ray
and use that in the Raycast
and is there a way of detecting what object the raycast hit
Of course
You should look at the docs for RaycastHit to see all the information you can get from it https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RaycastHit.html
perfect thanks
Hello guys, so I have a game with multiple scenes. However, when i change to another scene, it takes way too long to load. Is there a way to accelerate it?
put less stuff in the scene
also use the profiler to see if there's any code of yours happening during scene activation to slow things down
Is there a way to load it before so the switching is faster?
You could do async scene loading.
Sure, you can additively and asynchronously load the scene in the background while in an earlier scene
How do i do that?
Look up:
- Unity additive scene loading
- Unity asynchronous scene loading
- Unity
AsyncOperation.allowSceneActivation
Thank you!
today i learned that csharp doesnt have a modulo operator, it only has a remainder operator. so much pain and suffering.
For something like the player is it ideal to have a bunch of smaller classes attached and then like one "master" class that they all have references to that they use to interact with each other? Since I was told it's best to have the functions split across several classes.
why would you need a "master" class?
So the master class can have information like "am I dead" and if like the bullet raycasting in the weapon script and the FOV for sprinting in the movement script both need the main camera than the master can hold the main camera object reference.
That doesn't sound like a "master" script that sounds like a "health" script. And the camera stuff would not be related to it.
Isn't that exactly what a modulo operator is?
not quite
it behaves differently with negatives
modulo returns postive number within range in most languages. which is what you need with circular arrays.
it doesnt return a negative. for csharp, programmers wanted efficienty, so they dealt with this quirk as most of the time they only dealt in positive numbers (read from a stack overflow source, could be wrong)
it's easy enough to write a modulus function using the remainder operator if you need it
So the difference is that it doesn't preserve the sign(in C#)?
StackOverflow has many examples
the difference is that it DOES preserve the sign in csharp
But without a master script wouldn't each class need a reference to like 9 other scripts when they might only need to share like one reference? That doesn't seem ideal. Not trying to argue I just want to fully understand why things are best like that (:
A: event system B. interfaces
Ah, ok. Yeah, that's how I remember it working.
cant have negative indexs in a circular array tho, thats the problem
Just abs it then
I see...
yeah, i already solved it, its just a problem because how i implemented it, it caused me much pain till i figured it out.
yeah your explanation is pretty unclear. Sounds like you probably just want to project the desired movement direction on the plane of the wall
You can use Vector3.ProjectOnPlane for that
I'll just delete it for now and try to come up with a better way of explaining it lol. I did think about using ProjectOnPlane but I don't think that would work.
Why not?
happen to know a way i can overload the % operator so i can use that itself and not a function like mod()? i wanna use overloaded % operator with 2 ints
you can't overload the % operator between two ints.
You can only make custom operators with your own user-defined types
can you switch the % operator to another symbol so you can user define custom operator as %?
no
that sucks :/ all good, ill just make a user defined operator then
you can't define any custom operators between int and int
You can only overload operators for your own custom types
oh that, just sucks hardcore. so i need a wrapper for int so i can define custom operators
Sure but it seems like a simple function would be simpler, no?
you could make an extension function too
If you made a wrapper, you'd also need more functions to get it working in place of an int. Just use an extension method
i want originally to just replace the % operator so i dont have to worry about edge cases during my coding when dealing with mod, i can replace a % b with mod(a, b), just seems more simplistic if your able to replace the operator. i just wanted a way to keep the same style of using arithmatic operators to do simple arithmatic, but it just seems like the ways to do this wouldnt be better over a function.
thank you for all the help though, yeah going to just define a static mod function with 2 ints, better for my style.
Hello, I'm having a hard time understanding the difference between IEquatable and Linq Single. I have a structure and an array of this structure. I need to find and return the struct inside the array based on a single property. With Linq Single, I can do this
mystruct.Single(e => return e.property == value);
The issue is that each time I need to look into the array, I need to call this. I'm always checking for the same proerty, kinda like a dictionary with its key. (But I don't want a dictionary cause I want to be able to set up the array in the inspector)
I don't want a dictionary cause I want to be able to set up the array in the inspector
just FYI, there are assets that allow serializable dictionaries so you can use a dictionary that can be modified in the inspector
I thought I could make the comparison direct with IEquatable but it seems even if I implement the Equals and == methods, I would still need to loop on the array itself
Yes, that would be a solution but I'm wondering if this can be done with native IEquatable?
To reduce the amount of third party stuff in the project
hi, can anyone help me with unity ml-agents, im trying to train a drone using rl
no matter what getting a specific object from an array without just using the index is going to require looping over the array
thankuu
when making a progression based scene, like stuff appear after certain achievement, is there better way than setup the whole scene again when load back to it
Ok got it, thanks
I like the linq solution but I just want to avoid repeating the same code again when looking in the array. Can the lambda function be replaced by a normal one?
slots.Single(e => e.display == display)
Something like slots.Single(FindDisplay(e, display)) ?
that would require a lambda expression if you are passing in a different display each time you call the method. if not, then display can be a field and your FindDisplay method just needs to take whatever type e is as a parameter and as long as it returns a bool it would just be slots.Single(FindDisplay)
Got it. Thanks!
how do i reference a scriptobject or a prefab in a json file
you create a mapping from id to your unity object, then just store that ID in json
like add a id field in the scriptablaObejct script?
no you add it to some dictionary, if its on the scriptable object you'd still need access to the SO to get the ID then
where is this dictionary be? is it make a manager script, slap it on a gameobject, drag all the SO into it ?
Yes. That would work.
ok i jsut wanted to know how people does it
It would highly depend on the project specifics.
for my context is save/load the previous played character
I'd like to implement Firebase into my game, and can't decide between just using the REST API and downloading the full SDK
I'm not exactly sure if it's a must to download the SDK or if I can get away with just using the API. Currently I only need authentication and database
Hello, I've got an issue with my UI element. I create a card prefab and I add it to a game object who as a content fitter on it and the prefab scale down automaticaly. I tried to remove or change the Content Fitter but that doesn't work eighter.
Here is a quick demonstration of the issue.
P.S: The card bellow is the goal to achieve (I keep it to know the correct scale after I fix this issue)
I have issue with object finding.
There are lots of objects of different types. Nps can be looking for object of particular type. How to implement pathfinding of nearest object without brute force all objects of this type? It could be too ineffective
What have you tried yet, any code? Do you already use pathfinding with navmesh or similar? How do you instantiate them, how are they stored?
make an interface, register the object you need to do the pathfinding, use the interface as target
I haven't make any code yet. I also didn't create object storage. I don't do it because I don't realize how should I implement object finding. I didn't make pathfinding with navmesh, but I know that it using a*.
I have principal questions, that independent of my code
I may make misunderstanding with word "implement". My issue is algorithm. The could be lots of objects that nps can interact. My purpose is nearest object
3D or 2D?
2D
how many is a lot
how about quadtree or oct?
Up to 100-1000. Nps's 10-100
Result: up to 100000
100-1000 viable objects?
eg. when you say npcs are looking for a specific type of object, is that 100-1000 before or after it found those objects of said specific type
Does it matter?
How often do they check for those objects? Are they changing over the lifetime, so objecst can move, or npcs can move dynamically?
Yes
Do you need all updates at all times?
There could be 100-1000 objects of one type
Just sounds like you are trying to cover everything all at once without asking, what you need at what specific point
Did you look at the firebase docs? They have examples for unity and pretty sure they even have a guide for setting it up
Instead of searching through all the objects, use something like on trigger/collider enter/exit, to register objects in range and only search through them.
It depends on their behaviour. It could be every 0.5 seconds. For example, nps finding rock, throws it. Then find another rock
yep they do, but this involves downloading big sdk
and it greatly inflates my app size
i kinda want to use the API instead of downloading the SDK
Object position could be changed
Hey guys I think I'm poorly designing my animator, it's leading to some animation delay issues. I have 2 states, a "target locked" state and "free look state", the LockedOnHub is handling the animations in the target locked state. But when I run the animation, the Hub is causing animation delay because it doesnt move straight to the next animatio, rather it goes "StrafeLeft" -> Hub -> "StrafeRight".
QuadTree would be a solution
So you should think about update loops, that are not running constantly and not all at the same time, if you really need everything synced at all times. You should write down your system and what purpose those states serve. Is it important to know that throwing rock at all time?
my initial attempt at the animation was this spider web-ish configuration which was about to get very messy so i left it
But nps can trigger lots of objects. For example, bunch of rocks
So what? It should still be better than looping through all the objects every frame.
You might have several objects entering the npc trigger at some frames, totalling x * numberOfNpcs if they're moving.
And to be honest, at this scale you should probably think of using dots.
I am sorry, I don't realize what you mean. Why do I want know that throwing tock at all time. My English sucks
At that point you're gonna have more important problems than trigger messages.
Ah I havent really used this myself in a long time. Probably 
yea im really just seeking public opinion rn
one of the challenges im facing is encrypting my key
this kind of question ranges from very simple answers to very, very advanced answers depending on the scale and such
It is better but don't solve problem: don't use brute force with a*.
you are trying to make a system, that just handles everything at all times and hope for some magical system to catch up with that idea 😉 You should think about your core system in general, what updates do you need from the npcs. Does your player always see every update? Can they pause while being offscreen and so on. There is a lot more thinking to it before even touching any code to get a good structure in something that sounds like a live sim for npcs
Point-Region QuadTree first to find the object and A* to make your npc get to there
There are no better analogue for a* with dynamic objects?
theres probably a hundred
with a lot of different pros, cons, time and skill requirements
but you need to rebuild the tree to handle those objects to match the quadtree
Okey, I will try tall whole needed information
What do you mean by "A* with dynamic objects"? A* is a pathfinding algorithm. I don't see how it's related to finding items in the world?? Or are you trying to generate path to every item?
I want to make tags like liquid, fire, weapon, e.t.c. Each object has at least one tag. Now I don't know, should I add tags to the terrain (floor, walls).
NPS can interact with objects. Game os around manipulating NPS's, so their ai works beyond player vision.
When nps decides, what they wanna do, they compare distance to the objects with needed tags.
How could I make effective finding any object with needed tag?
P.S.
Nps could want object with two or more tags at the same time
i don't say this to be rude but to give some perspective, some people's whole full time job is doing what you are trying to do here
there isn't one single answer people can just point you towards, it really depends on how big your game is and how much you need to "solve" this
When I said dynamic objects, I mean object with changeable position. Some algorithm create paths to all objects,.but after charging position of object or nps, they needed to be recalculated.
A* have no care about changing nps's or object's position
I see. I wanted just direction or algorithm which I should take look about
How do I get references to objects I set in the editor to stick around/be properly recreated when I reload scenes?
I've got a singleton scoreManager to track my scores and update a text field to display the score, but as soon as I reload the level, the scoreManager loses the reference to the text field.
I get why, because the original text field object is gone, but how do I get the scoreManager to set a reference to the new one when I reload the scene?
When I reload the scene (to reset the level and increase the difficulty), the Score Text reference becomes None.
Keep it in the same scene/don't destroy state, or use a singleton in the same scene that's overridden by new instances on scene load
When I want something to persist between scene reloading, then I usually put it in a separate scene. Unity support additive scene loading, meaning you can have multiple separate scenes at once, and one of them can be used for persistent GameObjects. Alternatively you can use DontDestroyOnLoad to automatically move it to such scene (but try not to accidentally make duplicates).
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SceneManagement.LoadSceneMode.Additive.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
So in my case that would probably be a 'UI' scene on top of the main gameplay, right?
It can be.
Hello, I'm developing a Unity Multiplayer Vehicle Combat game, it's working correctly on windows.
But I want to host this game as a web server using webgl support.
I built it with webgl support and copied it to xampp/htdocs but it says it can't connect websocket localhost:7777
How can I fix this?
https://screenrec.com/share/bM8EmyFIlO
https://screenrec.com/share/xHiV0wdjR7
localhost might not be available on your server, because localhost is you locally.
You have to make sure, the port is available and also the correct ip is being targeted, which is not localhost
I tried to host it on my VPS and used that vps ip but it occurs same error
WebSocket connection to 'ws://myvpsip:7777/' failed:
Does your vps accept connections for that port and from outside in general?
I added 7777 port inbound on Windows Defender Firewall, do you mean this?
your VPS needs to open that port too, not just your windows system. or is your vps hosted on your machine?
I've been looking online for tutorials on how to make objects not exit another object, using things like edge collider and such, however the object in question I want to contain objects in is a 2D circle, if I were to use edgecollider2D, would i run the risk of having thousands of edge colliders and if so would that be a problem, or does unity handle circles with edge colliders well?
i figured it out, it doesnt freak out 👍
This is not a problem of navigation but of deciding where you want to navigate, so A* mention is not related to the problem in any way.
If you don't know what the destination is, no algorithm in the world is gonna help you.
If you need to know the path to a new position, you need to calculate it. There's no going around it.
The only ways you can optimize it is by:
- reducing the amount of iterations(limit the area in which items would be considered at all)
- spread it over time
- spread it over threads
I see. I assumed that there is some way to create "vector field" and slightly change it when object moves. I don't know if this exists
Guys, setting a bool to true makes unity not be able to enter playmode. I even made sure there is no infinite loop. What is going on here?
Not sure about "vector field", but you'll need to calculate paths to the items anyway. Unless you use some simpler distance calculation.
Thank you
But really, at such a scale, pathfinding is gonna be the smallest of your problems.
What is the biggest problem?
Well, maybe not the smallest, but you're gonna have many other problems too. If you're going for complex ai with more than 10 agents active simultaneously, you should probably look and dots/ecs.
Ai decision making, rendering, etc...
What do you mean "dots/ecs"?
Data oriented tech stack: jobs, ecs, burst compiler
#1062393052863414313
Hey Folks,
Have a general question about ECS. Let's say I have a camera, and input controls camera, it don't interact with ECS data in any way - at least for know, It's okay to put Camera controls just as Script onto game object, or should I aim to implement all of it as part of ECS anyway?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
IEnumerator RotateRandomly()
{
finished = false;
Vector3 randomAxis = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3), Random.Range(-3, 3)).normalized;
float randomAngle = Random.Range(-rotationAngle, rotationAngle);
randomRotation = Quaternion.AngleAxis(randomAngle, randomAxis);
rotationSpeed = Random.Range(0.02f, 0.04f);
while (Quaternion.Angle(transform.rotation, randomRotation) > 0.1f)
{
transform.localRotation = Quaternion.Slerp(transform.localRotation, randomRotation, rotationSpeed);
yield return null;
}
finished = true;
}
This never returns true. How come? I tried increasing the error threshold
You are using both .rotation and .localRotation here
I am going to be doing something in my game where there will be multiple computers in the world. And each computer will have its own "file system." This file system will be interactable on some computers(like the users), with the ability to save things like notes to text files, doodles/images to some image format etc. So assuming I have these computer gameobjects in the world, what's the best way to have these virtual file systems that I can attach to them? I'm thinking ScriptableObjects? But I'm uncertain amount the idea of modifying them. I already have a basic file system structure that I load/save to json. But I want to be able to set up and organize the file systems for each computer separately, so I imagine I need some sort of asset to link the configuration to
is alright i figured it out, its just cuz of their shape
Scriptable Objects if you're attaching data to these computers at editor time, but if you're saving runtime data then that runtime data should have the ID to that scriptable object so next time the game is ran then that SO is updated
I think its simpler than this, if each instance of the computer has a unique id, you can easily load and set the correct "file system" later
if you want some shared configuration that each instance shares that you dont expect to save during runtime, a SO is a good fit.
well they can be separate files or many instances can be in 1 file.
json isnt efficient for lots of data btw so consider alternatives if these can get big
well I imagine the json will mostly just be for saving the folder structure and reference locations for actual content
unless that will also be an issue
though the folder structure will not really be that large. Probably some standard folders like a documents folder, pictures folder and such with a few files per computer. It won't have an entire actual operating system amount of detail
hard for me to say, it could be just fine for you or become an issue later when things get very complex
probably fine to leave as json then!
these are binary serializers (better than the c# binary class serializer)
yeah I was gonna say I heard the C# binary serializer is not very good. I'll check those out, thanks!
np. where I work we use protobuf for remote update-able config + network communication (if applicable for the game).
for config we edit/store in json but load and save as proto binary to then be used at runtime.
amazing size savings! (e.g. 20KB -> 3KB)
If you are transferring JSON over network though, with compression the space saving of another serialization format is basically negligible. JSON is very compressible.
if you compress anything it will be better but it wont beat a purpose build serialization format
protobuf is good because data is identified by an int id and is specifically serialized/deserialized with generated code
It won't beat it, but the difference between JSON + compression vs protobuf + compression is a lot smaller, to the point where it's unnecessary in a lot of cases especially at the cost of having to bring in an entire library.
It's a different story if you are doing something like storing on disk because then you would need to write additional de/compression code, but for network transfer the compression is practically free in terms of implementation cost as every web server supports it.
yea i dont expect the compressed result to differ by much as both contain some same data. We use protobuf as it makes for an efficient cross platform binary serialization system (we have some servers written in scala). Was already a thing when I joined.
the messages are defined once and shared, once code is generated its already usable and reliable.
Yeah that advantage of protobuf definitely still exists, it's just the space saving aspect that's not really a factor.
If the application is fast high rate data transfer then its great as we can skip compression and worry less about size.
Im used to it so I like it 😄
I like json too but i know its deserialization can get to be quite slow with large files (depending on the lib): https://github.com/miloyip/nativejson-benchmark#parsing-time
Right, real-time data is an entirely different field as well.
Hey guys - I'm trying to copy over the transforms of a player to a ragdoll, and it's still T-Posing when I spawn the ragdoll in. I'm using this code to make it happen. Is there anything you can see as to why it wouldn't be working? I have confirmed that it is an identical hierarchy and the parts are lining up like we'd expect.
private void CopyBonePositions(Transform source, Transform target)
{
target.SetPositionAndRotation(source.position, source.rotation);
// Iterate through all source children and match them in target
foreach (Transform sourceChild in source)
{
Transform targetChild = FindChildInHierarchy(target, sourceChild.name);
if (targetChild != null)
{
CopyBonePositions(sourceChild, targetChild);
}
}
}
you'll have to debug the code
maybe targetChild is coming back null for example
you can't know until you debug
Lol yeah I've tried debugging and didn't see anything, which is why I came here to see if anyone saw something obvious that I didn't see
what do you mean by "didn't see anything"?
There are no nulls
what debugging steps did you take, and what were the results?
Any reason why it shouldn't be working
I printed out the parts that it was iterating through, and confirmed those are matching and I went through and confirmed that it was grabbing each child in the hierarchy and not skipping some.
then maybe some other code or component is overwriting the changes
do you have an Animator?
I have an animator on the source object, but not the ragdoll
The order of operations is that I spawn the ragdoll in, then copy the values over
if you do like Debug.DrawSphere on the positions being copied does it look right or does it look like the tpose?
maybe you're copying from the prefab instead of the object in the scene for example
Modding discussion is against the #📖┃code-of-conduct here
I've just gotten into building navmeshes at runtime with NavMeshSurface.BuildNavMesh(). I found GetBuildSettings() but there is no SetBuildSettings()? I'd like to restrict which layers the navmesh uses.
Hello, I have an issue with my 2D game. I created a camera that follow the player with an effect that apply bounds clamping after smoothing. So it kind of follow the player without being locked to the player.
The problem is when I move, the camera is following the player but it's not smooth at all. It's like the fps is very low while it is not. There is no problem if the camera is directly locked to the player but with my technique, it's flickening.
Can anyone revise my code and tell me the issue?
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.
obligatory: use cinemachine
are you replying to me?
that depends, are you currently struggling with camera code that could easily be replaced with a simple cinemachine camera?
I don't know what a cinemachine camera is. I'll look up on the internet.
check the documenation pinned in #🎥┃cinemachine
oh. I guess its that easy. I do be blind at times. ty :)
whenever i tab out of my unity game the frams drops to 10fps? i have run in background checked on as well does anyone know how to fix this?
Most computers throttle resources to programs that aren't focused
dang- sorry
Is there any tools I can use for generating 2D chunks easily?
2D chunks is not very specific
I am generating a world like the mini game Motherload. I need to generate the world in chunks around the player to avoid overloading.
Do you actually have a performance issue? Or are you just guessing?
I did create a chunks system but I do have some bugs in it so I was wondering if there is a tool that can manage that stuff to make it less complicated.
I don't have performance issue but my chunks system is a bit odd..
Maybe something on the asset store, but chunking is not very common in 2d afaik.
Maybe try without chunking first? There might not be an issue in the first place.
no I need chunks lol.. my world goes as deep as 500,000 tiles.
can't load that much in one go
It doesn't matter how deep it goes as long as only the tiles on the screen are rendered. Which should be happening by default.
Can you not generate it once on game start?
for that many tiles no
how long do you think it take to generate 60 millions tiles with random generation in it?
Depends on how you do it. Can be anywhere between less than a second and a few minutes.
wtf
Anyways, if you're set on doing chunking, you should either look for an asset, or try to fix your implementation. If you have a more specific question, feel free to ask.
how do you generate that many tiles in a few seconds?
If it's just assigning a value to a tile based on Boise, it could be pretty fast. Don't underestimate computers.
Then there are compute shaders, multithreading, burst compiler that can boost the process x10-x1000 times or even more.
It highly depends on your algorithm and requirements for the procedural generation
well I do generate caves system with noise that draw black dots on a white png then it apply that to the world generation.
Why does it even need be a PNG in the process. Sounds inefficient.
But anyway, all is assumptions until you test and profile it.
I'd say, test the simplest implementation (no chunking) possible and see how fast it goes.
Then you have some info to work with
for the rest, it's a simple system that create many layers. It start from generating dirt with 100% probability and slowly goes from 0% crustrock to 100% crustrock at a certain depth, then it does the same from crustrock to mantlerock.
Then I am generating ores everywhere on top of every tiles with a probability.
Guys why my WASD works like if i was moving character in worldspace or something? (But this only happens when i use Unity Recorder)
Very weird
I mean the recording package
is this a code question?
so far without the compute shaders, multithreading, burst compiler it's taking like 10 minutes (and yet still loading) to generate only 1 million tiles.
It sounds like it might be an issue with your algorithm. A million tiles definitely shouldn't take the much time. Try a smaller size(like 1000 tiles) and use the profiler to analyze the bottlenecks.
Tried with arrows and the same issue
is there any way to interupt the loading in process?
Well the package is made of code
or do I just click X
but if it is not your code that has anything to do with this then it is not a code issue
Then what do I do
How do I interupt the Application.EnterPlayMode ? I am stuck loading forever.
gotta kill the process
Most likely you have an infinite loop in your code
no I don't have infinite loop, I am generating 1 million tiles.
well you might have an infinite loop, or just one that takes a really long time
If the 1 million tiles are all GameObjects yeah you're going to have a bad time there
ok I think you spotted my problem then
unless you are doing things exponentially that shouldn't take 10 minutes so you probably do have some sort of infinite or exponential loop. but you do still need to kill the unity process to be able to stop it
You might be able to break out of it with a debugger. Attach the debugger, break manually and see what it's executing, if there's a loop, you could try modifying it's condition variables.
wait are you using individual gameobjects for tiles in a 2d game? use a tilemap and any extra data that you can't put in the individual files should just be in a 2d array
I'm using this to generate my tiles:
public List<Vector2> worldTiles = new List<Vector2>();
public List<GameObject> worldTileObjects = new List<GameObject>();
public List<RuleTile> worldRuleTileObjects = new List<RuleTile>();
public List<TileClass> worldTileClasses = new List<TileClass>();
adding to the list each tile
this is not generating anything
it's just a bunch of field declarations
and empty lists
no but im adding them to the list when generating them
sure, and yeah as mentioned if you're making a million GameObjects you're going to have a bad time
Ok I checked further, I do create a new GameObject each tile
I was assuming you're using the tilemap. Using gameObjects is gonna be inefficient even if you're doing chunking.
so switching to tilemap and then using compute shaders, multithreading, burst compiler will speed up my generation by 10000000 times lol
Possibly. Maybe even without compute shaders, multithreading and burst.
gameObjects might not be the only issue.
You really need to profile to understand the culprits
is there any way to layer a camera without pixel perfect and a camera with pixel perfect at the same time? Seems like you can either have everything be pixelated or nothing...
what would be the point of that?
My main game is not in pixel perfect, but I want to make a background effect using pixel perfect
with the rotating sprites thing
oh.. thought this was a code question. Maybe ask in #🖼️┃2d-tools
maybe you can toggle them but that sounds like more problems
I got a question about tilemap.. is it possible to have a tile that is not defined with rules, just one simple texture? I need to just do a procedural generation of tilemap instead of creating gameobject but it seems that creating tilemaps is only for rule tiles. I try selecting a tile on my terrain generation code from this:
[Header("Foreground Tiles")]
public TileBase dirt;
public TileBase grass;
public TileBase crustrock;
public TileBase mantlerock;
public TileBase mantlerock1;
But I can only select tile that has rules in them.
So how to create a tile without rules?
So I created a tile like this:
Then I assigned a sprite to it.
But I cannot select the tile I created at all
that's not how you create a tile, that creates a tilemap
tiles are assets. they are part of tile palettes.
oh ok so I must create a new tile palette inside here?
yes. also #🖼️┃2d-tools
thanks
I tried it and it doesnt work.
I forgot to take a screen shot, but very often i am getting the 'Value cannot be null. Parameter Name: _unity_self"
I am able to fix it just by restarting unity/relaunching, but is there anything i can do to help prevent getting this error, or something i can keep in mind that might be causing it?
it could be anything, from a bug to a corrupted asset or something
best you do some narrowing with process of elim
alright, might be difficult because it seems to appear randomly but ill track whenever it appears and what i did previously
one quick thing you can try is deleting library and refreshing the project, hope it was some lingering bad cache or something
also narrow down if its project specific or unity version itself, try blank project etc.
copy project into a new version of unity etc.
ty for the suggestions, will test them out
I need help in #🖼️┃2d-tools
don't crosspost. This isn't a code question
I want a customizable character system in my Game. Like the Player can equip Armor, weapons, hat's, Boots and whatever. Should of course be visual too.
Would you choose 3D for this, some 3D Modell that you equip with different meshes Like Armor, weapons e.g. or would you choose 2D instead? But If 2D, how would you make the Sprites modular and animated at the same time? 🤔 Glad for any Help!
you can achieve this in both 2d and 3d.
whether you choose 2d or 3d is up to what kind of game you want to make, it's a question of design
Isnt it way Harder in 2D? Atleast thats what i Heard
depends on your skillset
Well for 3d you simply attach meshes in the right Slots and it works instantly. How would you realize an modular 2D character where you can easily Swap items, armors or the Players Race for example?
It’s pretty much the same in 3D and 2D except you’re working with meshes instead of sprites in 3D
But how do animations work then? I mean, you can reuse 3D anims easily on all humanoid characters. But sprite animations are unique, so if i say i have a human 2D sprite, i need like an animation for all combinations of possible items and wearables? Which is like parabolic? Or is this solved differently?
You would split up your sprite character in to multiple pieces so that you can compose it using any combination of them
The solution you go with here is heavily dependent on your requirements
How would this look tho? Like splitting it up in torso, legs, arms, head and whatever? But how would i animate them together then? Im confused, are there any examples? ^^
Well what sort of animation are you trying to achieve? You can use a bones approoach and animate the bones similar to how you would animate a 3d character
Well something like this. But modular, like you can equip different items, hats, armor pieces or whatever. With my limited knowledge i assume this is impossible modular since you need to have like parabolic animations for like each variation?
Doesn't have to be, but there will be limitations to what you can do. For instance if you look at only the helmet in that animation you could say it's only 3 different sprite frames. Assuming you give each helmet you make those frames you could animate both the position and sprite using a bones approach
Typically bones moving from one position to another is smoothed to give you nice smooth animation, but you could ignore the smoothing and jump from keyframe to keyframe to give it a snappy animation
- it's not impossible by any means.
- it's not really more work, it's just a different kind of work. you might be more familiar with 3d so the unfamiliar 2d workflow seems much more complex to you; it really isn't
- this isn't a code question. if you have further questions consider asking in #🔀┃art-asset-workflow
CharacterController has a bool called EnableOverlapRecovery. Is there a way to detect, when CharacterController "recovers overlap" to see if player being crushed by a moving wall for example?
I guess, using the standard collision checks will return what you are trying to get
you mean OnControllerColliderHit(ControllerColliderHit hit)?
Or collisionenter and so on, those should work too
referring to the docs: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController.html
I thought of this, but I don't really know how to detect if other collider penetrates the character controller. Maybe some checks if hit.point is within collider and not on it's surface will do the thing, but I didn't figured it out yet
Did you read the docs about that part? ". This only concerns static objects, dynamic objects are ignored by overlap recovery."
yes, I can't really use overlap recovery because of this
I mean, maybe there's built-in way to detect colliders penetrations
Penetration is, when you enter a collision.
if you want to avoid that, collisionenter is basically your callback to react to.
*on dynamic objects
long story short, how do I divide longs? I am fine losing like 3-5 digits of precision
You divide longs with the / operator
If you don't want integer division, cast them to double first
would that work just fine with the biggest/smallest longs?
In what sense? What do you mean by "work just fine"?
long is the same as int, it just has twice as many digits
so I was not sure if long is always lesser than max double
63 binary digits vs 31 for int
yet now I have searched again and yeah
double like float can be very huge
sure bigger than any long
yes max long is less than max double but that doesn't mean double is very precise when dealing with extremely large numbers
what are you trying to do and why are these questions coming up?
getting time from a server as long
using that to make daily rewards
doing division for a timer
where does the division come in
I don't have to do that for this, yeah
I just represented the timer as a value from 0 to 1 and wondering why does it not working
then I figured it's long being rounded
long cannot hold non-integer values
it's an integral data type like int
yeah figured somewhere along the way
there's also no reason you would be dealing with anything anywhere approaching "the largest long values" when dealing with such a timer
I mean what if double is small and I can't cast big long into one in the first place
cleary not the case but I didn't know
I'm not sure what you mean exactly
like what if I have a long of 9999 but double is overflown at 999
The only time you would be dealing with division for a timer is to do something like "what percent of the day am I through" for example, right?
yeah
in that case you would only be doing division with relatively small numbers anyway
assuming your long represents seconds or ticks, you would do:
long timeThroughDay = currentTime - dayStartTime;
double progressThroughDay = (double)timeThroughDay / timeUnitsPerDay;```
exactly what I doing
then what are you worried about
fair
Even if your time unit is Ticks (C#'s ticks which are one ten millionth of a second) the number in a day is this: https://learn.microsoft.com/en-us/dotnet/api/System.TimeSpan.TicksPerDay?view=net-9.0
double has more than enough precision to do division with numbers of this size and smaller
I got used to think of worst cases
haven't think that I won't encounter the worst case in this particular division
also a word of advice it might be better to write this code using DateTime and TimeSpan than just long
If you can work with time span, otherwise use DateTimeOffset to work with Unis MS
I often work with unix ms directly as we prefer to store date+time in this way but be smart and use TimeSpan/DateTime/DateTimeOffset when you can to make life easier 🙂
Also this isn't a problem even if you had very large numbers, all that would happen is that you'd lose some precision (which you said you're ok with.) Double doesn't "overflow" the same way as integers. If (theoretically) the max integer precision of double was 999 then casting 9999 to double would result in a nearby number like 9996 or 10001 for example.
but the real limit for double is 2^53 which is 9,007,199,254,740,992
Hi! I'm trying to implement "cobo" system - player must enter several keys in order to cast spell. For example on gamepad a-a-x-b => Fireball. (or you may be saw how it's done in Helldivers 1-2 with arrows)
I thought implementing New Input System to handle key clicks, so it's configurable. But now I'm a bit confused how can I create combos via editor.
The idea was to create SO and put list of actions there, but I can't figure out if it's possible, because I can't drag-n-drop actions from Input System config.
Could you please help me figure it out? May be It's incorrect approach and I can do it differently?
I wouldn't try to do this directly using a list of actions.
You're going to want at least one layer of abstraction in between the input handling and the combo logic
Hmm.. for example I can create Enum for Actions, and then convert it to what I need. This way I can use it in SO. And then in Managers/Services do conversions/combo logic?
not an enum for actions
an enum for your concept of a button or whatever in the game
Yep, like enum { Abutton, Bbutton, etc..}
like cs public enum InputCommand { Up, Forward, Back, Down, HighKick, LowKick, HighPunch, LowPunch }
if you will have gamepad and keyboard input id suggest more generic naming for these enums. But as long as inputs map to one it should work fine.
Like when you see a move list for street fighter - you want those things
ah yea thats a good idea
Yep, this is what I want to achieve. You gave me good idea where to start, thanks a lot!
I've being thinking for some time and couldn't figure it out, and as always - solution is as simple as it could be 🙂
Unless it's Street Fighter II specifically
well they are 64/32 digits, just offset
one bit is a sign
no, it's in two's complement, not sign-magnitude
twos complement still uses a sign bit
Two's complement uses the binary digit with the greatest value as the sign to indicate whether the binary number is positive or negative; when the most significant bit is 1 the number is signed as negative and when the most significant bit is 0 the number is signed as positive.
a uint32's 31st bit has value 2147483648
a int32's 31st bit in two's complement has value -2147483648
unlike sign-magnitude where the sign bit is literally just the sign
as far as ive seen, "sign bit" is usually for when the bit is literally just for a sign, like in IEEE 754 floats or sign-magnitude
look we both understand how it works. I don't think a pedantic semantic argument here will be productive.
sure, but i wouldn't assume the person you're answering to does; imo saying that a 64-bit type has 63 value bits is misleading
it still has 2**64 possible values
Has anyone used RealWear with Unity?
I want to break my work into multiple scenes. I'm trying to achieve a behaviour where awake is called on all active objects across 2+ different scenes before start is called on any object across any of the loaded scenes.
Idea is self init in awake -> reference other classes in start but consistent across 2+ scenes.
I need a clean reset between each transitions. Idea was to use SceneLoadMode.Single on the first of the scenes, and then additive for every subsequent scenes. Set the allowSceneActivation flag to false on the ops handle, and turn them all on when every scene is ready. Problem is progress does not seem to begin on the additive scenes if the one loaded as single hasn't completed. Any idea?
Its easier to init things yourself manually in such a situation imo
I think you're better off just controlling the initialization process on your own rather than trying to rely on Unity callbacks here
smart guy
Ugh, there's a lot of work done that'll need refactored. Was hoping for a hack. Thanks, I'll go this way then
One option is to have all these scripts subscribe to a static event or two in OnEnable and invoke them when you know everything is ready to be initialized.
that way you don't need the central manager to have references to everything
It can be made easier by using an interface you make with the Init function so you can get all components with this interface to init them all.
Id avoid static in this situation as this should be per scene
if (velocity.x > 0 && drag.x > velocity.x)
{
drag.x = velocity.x;
}
if (velocity.x < 0 && drag.x < velocity.x)
{
drag.x = velocity.x;
}
if (velocity.y > 0 && drag.y > velocity.y)
{
drag.y = velocity.y;
}
if (velocity.y < 0 && drag.y < velocity.y)
{
drag.y = velocity.y;
}
velocity -= drag;
Is there an easier way to do this? Basically, I don't want the drag to be stronger than the velocity .
So i'm encountering an interesting bug, i've got a chain lightning effect on my game, and when it triggers it does an animation setting the scale of it's collider from 0-15 over 4 seconds (Followed a tutorial) The odd part is it's interacting with my Plot systems, and as they're "firing" it's causing the OnMouseEnter/Exit script to play from my plots... But the mouse is just sitting on the plot.
{
sr.color = hoverColor;
}
private void OnMouseExit()
{
sr.color = startColor;
}```
I've looked at layers and i think i'm missing something maybe slightly obvious here lol.
If there's multiple of them firing, it seems to not even register any mouse at all.
If the scale is changing when you hover things, they might be scaling out of hover range, which causes them to scale back to normal, which would cause them to be hovered again, and so on
OnMouse events trigger only on the first collider under the mouse. So if the lightning effect has colliders (it's not clear which collider's scale you're changing) and the effect is on top of the plots then they'll block the OnMouse events
So the Plot object itself shouldnt even scale; it's just a static object on a grid that when interacted with places a tower. The scaling component is from the lightning projectile.
AHHH, is there any way to make it so onmouse disregards those.. hah
Do you ever need the lightning to be interacted with any sort of physics query? You could put it on the IgnoreRaycast layer, pretty sure OnMouseEnter uses a raycast internally
So basically the only thing the lightning does, is when it's collidor triggers entering an enemy's collidor it creates a child of itself and jumps then does a particle trail between the two.
So it does use ontriggerenter
Pretty sure IgnoreRaycast shouldn't affect rigidbody messages, just the Physics.WhateverCast kinds of things
Might be worth a try?
yeah im gonna see here
Learning more about Raycasting and UI elements this project than i have in the past lol;
You're a gentleperson and a scholar; this worked, by setting it to the ignoreraycast layer
Good to know that it doesn't affect physics events too - I legitimately wasn't sure
Now a question regarding particle systems, Does anyone have a good video going over them?
I'm trying to make the size of the "crackling lightning" particle there not as lengthy. lol.
check the pinned messages in #✨┃vfx-and-particles
Didn't see that far down!
Hey I'm trying to fix an edge case scenario with my movement script that happens when moving up a slope, onto flat ground
my player character gains more y height than is needed to line up with the flat ground, and as a result, ends up briefly being registered as not grounded.
I've been debugging this for a while and narrowed the issue down to that, but I'm not sure how to address it in a way that wont raise other issues (i.e. I can widen the threhhold for how far the ground can be to be considered grounded, but this results in the same problem reoccuring when traveling down a slope from flat ground)
if (hit.distance <= skinWidth + 0.0001f ) collisions.below = directionY == -1;
I have also tried checking if the player was climbing a slope within the last 3 updates, and setting collission.below true if so, but this only mitigates the issue... it still occurs, just less often
any other ideas on how to adress this?
and here is the code from determining my velocity when climbing up a slope
void ClimbSlope(ref Vector2 velocity, float slopeAngle)
{
float moveDistance = Mathf.Abs(velocity.x);
float climbVelocityY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance;
if (velocity.y <= climbVelocityY)
{
if (player.isDashing)
velocity.y += climbVelocityY;
else
velocity.y = climbVelocityY;
velocity.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(velocity.x);
collisions.below = true;
collisions.climbingSlope = true;
collisions.slopeAngle = slopeAngle;
}
}
and heres the full script... if anyone could take a look and help me with this it would be appreciated, been stuck on this forever...
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.
did you get this code from somewhere? it seems quite weird and honestly you shouldnt need trig math here, or in many places at all. usually for slope movement you can just project the vector using the normal of what you're standing on.
Also is there an actual problem with it not being grounded for a second? This is kinda just how it'll work if you're moving up a slope. Imagine for example if your move distance was set to a very large number and you were at the top of this slope. It'd look like you were launched up. When you move up the slope, theres nothing checking if you should be moving forward onto that flat surface. That same thing is happening in your code, just to a smaller degree
yea, I made this controller originally alongside an old youtube tutorial, though I haven't to find it again since... I've made alot of changes to it since. it works well, does everything I need it to do, and I've fixed most of the other issues with it, except for this one
that surely is some code. I guess one "fix" would just be having some kind of snap to ground logic where you just manually force the player down if they're close enough to the flat surface. You'd need to code in exceptions so this doesn't run when the player is trying to jump though
heres a visual that shows the frame its happening on
again, I believe whats happening is that when moving up this slope, I get more y velocity than I need to reach the flat ground, resulting in my hitbox being beyond the skinWidth threshold needed to set collisions.below true
I mean yea thats pretty much exactly what I described here #archived-code-general message
i really question what problem this is causing you though. If its just that you can't jump or something because you aren't grounded, you could implement a coyote jump timer. Basically meaning allowing the user to jump for a very small window after not being grounded
the problem is almost entirely visual/audio
it puts the player intoa falling animation for 1 frame, which also causes a landing sound effect
I guess snapping the player to the ground then might be a better solution
possibly... how would I detect when to do that though?
You could just check for it constantly except for when you jumped recently. Also you could change the logic so that they arent put into a falling state if it's for a very short period of time
Youd have the same issue if you went from a flat surface to another slightly lower flat surface
hmm yea, ok
that latter solutions seems to work
I was worried that would cause some visual weirdness when walking off ledges, but its not really noticeable
anybody know how to fix this?
Unity Collab no longer exists. You should probably remove that package
ah okay
i did a clean install of VS and it fixed it but clearly thats what changed haha
Looks like the error was in PackageCache so reinstalling it probably cleared the cache as well
does anyone else find that visual studio randomly stops showing errors that absolutely should be shown, until you restart visual studio
everything is configured perfectly fine, there's no issue with that
i could write some gibberish like Rigidbody2Dfndsfhfhjsf and unity picks up the error but visual studio wouldnt see anything wrong
close and reopen VS, suddenly the error appears
VS or VSCode? Because VSCode definitely does this often
visual studio
whats weird is I tend to notice its only specific to unity types, publicjdkfjsdklf floatdfjshfj foo would always detected
are you perhaps using an older patch of vs? i remember that was an issue a while ago but was then patched, it usually happened when creating a new file or when the solution was just not refreshed when something changed
as far as I know everything is up to date
im not at my pc right now, but ive troubleshooted this before and updating was the first thing I checked
its almost like it "forgets" how to find errors, yet everything else like intellisense works fine as it still knows all the different types and whatever
it does seem like it typically happens after I make new scripts
its annoying that searching the problem online, only shows posts of people who havent configured the ide at all
Hi, trying to make a tycoon game for the phone and making a system that if you watch an ad, it rewards you with 2x multiplier... however, using Ads Legacy, the OnUnityAdsShowComplete doesnt register as complete
No errors in console either
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You want to use level play/ironsource now and hopefully be on a semi recent unity version like 6 (2022 min)
are you sure it doesn't? Your if condition there is suspicious
Is there something about Vector3 which is making it lose precision?? I feel like i'm losing my mind
floats are not precise
bug in the debug logs that screenshot whoops, problem is real though. Clamping gravityFactor to 4 digits helps but doesn't wholely solve
Maybe provide some more info on the issue and how you confirm it.
Yeah need new screenshots
My function, console log with what my lil guy is doing
I guess I just need to use the System.Math functions to get doubles on everything
or work in some new unity script which can do the same thing
This still does not explain what the problem is
_state.gravityForceApplied and _state.Velocity.magnitude are not keeping pace with each other despite (in theory) being scaled equally
In-game it means if I set up two hills next to each other i'll slide down one and not be able to get up the other one fully as the energy isn't being conserved
The energy is not conserved in real life either. There's friction and stuff.
And anyways, it's note entirely clear how/what conclusions you make based on these logs.
Do you expect the velocity to change by the same amount as force or something?
Logs are saying the difference between current and last velocity per tick is equal to the difference between current and last gravityForceApplied per tick. More or less, a few precision errors in there. This is good!
But if I check the difference between Velocity.magnitude and GravityForceApplied each tick it keeps increasing
must be the gravityDirection vector which is messing it up
Velocity magnitude and gravity force don't have to have a linear relationship.
its the same number, so we expect it to
But it's not correct to use the difference between velocity and force in the first place. One is distance / time. The other is distance / (time^2).
So I'm not sure what kind of metric are you expecting to get with velocity - force.
you're correct the naming scheme is a little wack, the whole gravityforce variables are just part of the testing because its not behaving as expected
force is in kg m s^-2
Indeed, but by default in unity mass is 1, so it can be ignored.
ik, but just seemed that was missing
What do you mean by that lmao
Hi! Could please some one help me understand VContainer better. It has so called LifetimeScope - I can't wrap my mind around it, it's expected to be one for scene or It's good approach to have several ones, for example for each unit on scene?
What's Vcontainer? Is it unity API?
It's DI framework for Unity. https://vcontainer.hadashikick.jp/
A third part framework, ok.
Lifetime scope usually means how long the object is alive, when it's released/destroyed.
In this specific framework it also seems to be a framework specific concept, so you'll need to read the docs.
yep, docs a bit vague on this. I'm using it without issue at the moment, just don't want to refactor a lot later. Wil continue research -)
it allows you to bind the instance created in the container to the lifetime of another object (the one with the lifetime scope component), whether you have one or multiple depends on your architecture, both are fine.
its important to understand though that DI containers as a pattern do not actually support runtime modification, which makes the pattern unsuitable for gamedev where objects are constantly created and destroyed (in most projects). the unity specific DI containers all try to extend the pattern to support lifetimes, and the lifetime scope is VContainer's idea of that.
You get the most benefit and and least headache from DI when you use runtime scopes sparingly (meaning the rules for them are simple and few) or in a very well documented/understandable way that you provide debug-tools and validation for.
typically a good reason for multiple lifetime scopes are scenes and large fundamental blocks you have in your game, maybe zones, UI, UI panels etc.
Yep, I was thinking about separating UI to another scope, since I feel putting all in one getting messy. As for creation of scopes in runtime I've already faced bunch of issues with that and now doing this verey carefully, usually having 1 manager created at the beginning and objects just registering to it to be processed.
the biggest danger of DI, as a "beginner" is that you overuse it
but its natural to do so when learning such an invasive pattern
Yep, it's big challenge. I had expirience with DI in Java (a lot), but with Unity it's more like "support tool" rather than cornerstone of your app.
in Java (and .NET) DI vibes very differently
I used it to inject EVERYTHING at first.. ) It wasn't fun)
cause in those contexts you generally use it to statically define the creation rules of everything, often from a config file
most of that stuff is too basic for use in a program that dynamically changes itself constantly (like a game)
inject everything is the great "global access fallacy" of DI
just because one uses DI containers, one isn't suddenly and magically solving the global access issue
some say that DI containers make it too easy to create dependencies and this is ultimately what can ruin a codebase over time.
I would say it's not about global access issue. It's about how easy I can get required dependency where I needed and also not lose all configs because I changed name of my class or object.
It's a bit safer to do it in code.
and in VContainer you're also supposed to use a MessagePipe for communication. Which is a whole other potential can of worms.