#archived-code-general
1 messages Β· Page 171 of 1
.velocity = Vector3.zero
hello! I'm running into a bit of an issue when trying to play animations for some models in my project. I'm using the Animation component and pretty much just doing Animation.Stop(); Animation.clip = selectedClip; Animation.Play();
every time i want to do a new animation. This works great generally but I noticed that if I stop an animation in the middle of it, then it'll actually keep it's pose instead of resetting back to how it was at the start... I'm not sure how I can fix this and I'd rather not use an Animator since that just adds a lot more overhead than I need for this thing, but if I have to I'll use one
Guys for some reason my auto complete has suddenly stopped working. When I hit enter or tab this happens
it just doesn't fill it in
Finally! Fix VS Code Auto-Complete for Unity on Windows! You will link VS code to Unity, install extensions and build tools and learn to use Omnisharp.
- CHAPTERS *
00:00 - What You Need To Do To Fix AutoComplete
00:11 - Starting A New Unity Project And Script
00:33 - How To Link VS Code To Unity
01:10 - How To Update Visual Studio Code Editor...
It's what happens at the very start of this video
on the left
I tried to following the steps on there but it's outdated and hasn't helped
I think it now uses devtools and not omnisharp?
it works when filling in other things like variable names and imports
but not functions?
idk if I screwed something over by accident? It's just weird
this isnt the righ way to do this
this is old
clickbait title
right, so what should I do then?
use mine
https://youtu.be/4KhjzVHQvrg
Microsoft has released a VSCode extension for unity which no longer requires you to go through a a painful process to get code completion , error highlighting and intellisense working.
original guide:
https://code.visualstudio.com/docs/other/unity
Unity for vs code:
https://marketplace.visualstudio.com/items?itemName=visualstudiotoolsforunity.v...
its better
lol ok I'll check it out
public class camera : MonoBehaviour
{
public Transform player_transform;
public Transform camera_transform;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
camera_transform.position = new Vector2(player_transform.position.x,player_transform.position.y);
}
}
```why doesn't this work?
How can I know that someone is bought a subscribed in my game using the unity in app purchases?
define "doesn't work"
also don't crosspost
you already asked in #π»βcode-beginner
circle flies away from screen
sorry master
idk why ur saying it's clickbait cause it said to do the same stuff as u did in ur video, but also with aditional outdated stuff
still not working unfortunately
because 2023 instructions dont require VS build tools
so it's not 2023
right
I didn't do anything with build tools
ignored that part of the vid
I'm getting the same issue anyhow
it all works except when trying to autofill a function
im sorry but they are not even close to being th same..
mine uses the actual Unity extention microsoft dropped
that is part of the new workflow
guys?
wdym fly away ?
there was a pinned comment left in the description of the video saying to install unity and it mentioned about updating the cs extension in the vid
anyhow, when I try and autofill this
it just doesn't work, or sometimes deletes characters
seems to be working
nevermind i found problem π π i forgot z axis, camera stuck in circle = me se nothing
the correct suggestions appear, it's just that it doesn't autofill it in when I press enter/tab
was just gonna say z prob isn't correct
it works for everything like variables and imports but the autofill doesn't work on methods
idk VSCode is kinda garbage like that tbh, even configured it gives me wrong intellisense
or just not at all sometimes
if you want a good expeirence use VS Community like everyone else π
everyone here highly recommend it
this was working yesterday though. It just suddenly stopped working and it doesn't work for any method
VSCode things β’
I'd wait till the Unity extension at least goes beyond 1.0
it's not even full release yet, expect bugs
plenty of bugs
Ok I think I fixed the performance problem
I have an Awake() that does
controls.Player.Enable()```
And it seems like when I later do:
```SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);```
It creates a new Controls() every time, and the old ones stick around?
I added
``` private void OnDestroy()
{
controls.Player.Disable();
controls = null;
}```
and it seems like the problem is gone now.
I'm a little surprised the Controls() don't just get garbage collected though
https://docs.unity3d.com/ScriptReference/Animation.Rewind.html
Perhaps this method is what you need? Stop -> Rewind to set it to frame 1?
This is probably a really easy fix that Iβm just too stupid to find but itβs saying β(58, 1) error CS1033 type or namespace definition or end of file expectedβ
I have not used unity or C# in like a year so I forget a lot of stuff
configure your !IDE so it points out errors like missing brackets
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
you terminate scopes with the } character, you havent terminated the class { .. } scope
also this yeah, definitely do this
also line 15 is definitely wrong
Thanks for the suggestion! I just tried it out and it still has the same issue... Maybe it can only work if I wait until the next animation frame to start a new animation? Either way, I think I may just have to bite the bullet and use the Animator instead
always start with the first error shown in your error list, not the last
youd have to be more specific about your issue, but yeah I also recommend using the animator, it works quite well
And like 24 is an issue
Ok I fixed the errors but my jump function is acting weird
The jumps are very inconsistent with how they act
Sometimes it jumps a good height and sometimes it barely moves
any ideas how do I make unity ragdoll land on its feet standing up ?
I know something to do with active ragdoll but how and which rigidbody do I keep up? hips ? legs ? feet?
do i ignore this...?
Remove time.deltaTime from addforce
You'll have to adjust the force after that too
Also, how do you get jump height? Is it changing, because you do a new jumpforce from it every time you jump
Probably. Check in https://discord.com/channels/489222168727519232/1064581837055348857
There are definitely tutorials for this, you dont need an active ragdoll purely for standing up. If your character is an active ragdoll to start then it would just be via configurable joint target rotations
I can't get visual studio code to work... I keep getting no ability to reference anything outside the current file - no packages, no unity things, nothing
I mean in the suggestions bar
I did the proper setup in #854851968446365696 of course, it still happens
the while crashed it as it was never going to be false, so was stuck in an endless loop
no idea why it should never be false, I mean at some point I stop clicking right
but I got it
if (Input.GetMouseButtonDown(0))
{
startPoint = camera.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
endPoint = camera.ScreenToWorldPoint(Input.mousePosition);
}
works
not on that frame though
oh
right
if I would have done that on a FixedUpdate would that at least not crash?
the frame wont finish drawing until after your code finishes executing for that frame.
It wont update the values of the inputs until the next frame.
Therefore, for that specific frame, your while loop will consider the button to forever be pressed, because the frame is never allowed to complete
i get it like the frame would get stuck so it will never get to call the method again to check if i released the mouse
but if its a fixed update and its based on time instead on the frame (like it doesn't matter if that frame is stuck)
You almost never need to use while loops, you should avoid them as much as you can unless you 100% for sure know what you are doing, to be completely honest. While loops are the easiest way to lock your game up because you made an assumption about how something works.
will do
now I am just asking out of curiosity to understand the mechanics better
almost every time you use a while loop, you can just use a for loop instead that has some kind of base case "something went wrong" catch that will fail a bit smoother and not crash unity :x
i am satisifed with this
exactly yup π
so if I used the FixedUpdate?
still really bad practice but would at least not crash?
cant read inputs in fixed update, fixed update is meant for physics/drawing stuff
but I can read inputs in a fixed update
it just runs at different times than the normal update right?
Update runs at every frame, unless that frame is stuck and FixedUpdate runs at fixed time jumps?
you can accidently "read" inputs twice, or miss them, in fixed update
yeah
but also I believe you'd still get the same infinite loop issue anywho
oh aight
its all running on the same thread still, if you lock that thread, you lock everything
cross posting is against the rules, you dont need to cross post, most of the folks who help browse all three channels regularily
now just a random math question while I am still on this, subtracting two vectors yields the vector in the opposite direction right?
like
powerPoint = startPoint-endPoint
something feels very incorrect with that nvm ill go read thank you
fix: i am stupid and its as simple as that
Doing endPoint - startPoint is probably what you want, because itll be a direction vector from start to end. Right now your direction would be end to start, which is the opposite direction
my only problem right now is that ball having a god complex and refusing to collide oh my god i forgot to add a collider
If your object was at start, it would go towards -endPoint
Also you dont need fixed update for that, just add force once when launch is supposed to be set true
i realized having the object be the center or start would be the best idea
Yea you can fully move that to update
yeah but you know everyone says physics at FixedUpdate
it also helps keep stuff cleaner
Impulse, velocitychange, and direct changes to velocity dont matter where they are
but should I?
Because you arent using DT (deltatime) in those forcemode equations, it being in fixed update doesnt matter
It doesnt really make a difference, I'm personally not a fan of running fixed update just to check if launch, when launch could be removed entirely
nice
does somoene know how unity calculates its mesh.recalculate bounds, I tried my own functions but my result is not nearly as good as the normals form unity
I created a level select screen using buttons, however, I get a null reference exception (object reference is not set to an instance of an object). The level select screen functions fine in the Unity editor but not when playing from a WebGL file. I have not been able to find any tutorials that explain how to avoid null reference exceptions when using buttons.interactable. The null reference exception is flagged at the very first instance in the code where i set EasyYellowButton.interactable = false; (Line 49 of the code here --> https://gdl.space/pupoquraca.cpp) Any suggestions or help would be appreciated. Thanks,
So, EasyYellowButton is null
thats a lot of if statements
I seem to get a null reference exception whenever button.interactable code is executed. Is there a way to check if EasyYellowButton is null?
if (EasyYellowButton == null) { }
I really think you need some basic programming courses
thanks. i'm going braindead since i've been debugging this for some time. i tried that and EasyYellowButton is null immediately before line 49, but not null after line 77
Not possible
after line 77 would imply line 197 or 433, both of which arent in the same function.
i check if EasyYellowButton is null before line 49 and the debug.log prints that it is null. After line 77 i check for 2 conditions, if EasyYellowButton == null the debug.log will print null (t does not print this) and then i also check if EasyYellowButton != null and it does print the debug.log that says it is not null.
post latest code
clarification.... I noticed that when the game starts, EasyYellowButton is not null, but when I click the white button, it prints out that EasyYellowButton is null. https://gdl.space/sezavihiri.cs
That code makes absolutely no sense.
If EasyYellowButton is null then the rest of the code will not execute so there can be no other Debugs
it's been driving me crazy for the last couple of days
well learn how to program
thanks, i'm trying my best
Let me help you a little```cs
if(EasyYellowButton == null)
{
Debug.Log("Line 50: EasyYellowButton is null.");
} else
EasyYellowButton.interactable = false;
Ok, i pasted that in. When the game starts, EasyYelloyButton is not null
So this
'i check if EasyYellowButton is null before line 49 and the debug.log prints that it is null. '
is not true?
i need help , why the light like the light of a flashlight i dont see in game but in scene i seeΒΏ
and after i click the white button (first unlocked level), then the null check i have at line 81 prints out that it is null
Hello everyone!
I'm working on a MOBA Style game, with point and click movement. Originally, what seemed like a good idea was to use the navMesh and navMeshAgents, but turns out they did not work for me because of the following:
- I want snappy movement, no acceleration / slowdown on path start or end.
- For some I don't understand the agets slowed down a lot when making turns (being close to the navMesh zone end).
- And they would also slow down A LOT when the path of 2 agents intercepeted eachother, and they would act as if a massive velcro strap was between them and take forever to pass eachother. That is, with double-cheked agent dimentions and all that stuff.
What I eneded up with was baking th navMesh, but scraping the agents, and just creating a navMeshPath, take the path corners and have the characters follow the path points until the destination at my complete control of speed, slowdown, path canceling...
My problem now is that even though they respect the navMesh zone they do not care at all about eachother, which is expected they way I've set things up, but I'm running out of ideas on how to implement it.
I've looked into rigydbodies, but they end up going absolutley crazy when reaching the path destination ( whiplash style flying ). Any ideas? Should I ree-add the navMeshAgent, calulate paths through that, but stop them imediatley and still run through the points with my own movement? what should I do?
clarification.... first, line 86 says not null, then after clicking the EasyWhiteButton, EasyYellowButton becomes null (line 50)
hi,
is it possible to search a string for digits or floats or int and replace them with something else ?
for example if string contain x.x ( float) or x ( int) or (x,x,x) (vector3) .... if true>>> replace this part with another string
Look into Regex
Dudes, how do you handle state behaviours on substate machines?
I want it to enter just once when entering that sub state machine which has a state behaviour on as well as for exiting.
It seems OnStateEnter and OnStateExit are called for each state inside a sub state mechine
Sub-state machine is just visual convenience feature, no such support
private void Start()
{
MyPlayerInput.instance.shootAction.performed += _ => Shoot();
MyPlayerInput.instance.shootAction.started += _ => Shoot();
Debug.Log(gameObject.GetInstanceID());
MyPlayerInput.instance.reloadAction.started += _ => Reload();
}```
for some reason my input isn't using the shoot Action as a hold
its being used as a press action
So, what is your suggestion?
I want an event to be raised just when entering one of these states and as long as the current state is one of them, it should not raise anything until transitioning into another different state outside the substate
dont crosspost
?
I have to check the prev state in the state behavior and compare if the prev and the current state behavior have same kinda tag and based on, decide trigger some events.
I have implemented a generic state behavior.
I'm having some trouble with Simulator, Safe Area, Unity Remote, and UI Toolkit. The simulator seems to be scaling everything up, so when I try to adjust my VisualElement position and size to the Screen.safeArea, it's moving too much/too big. Anyone have any experience with this, and can point me in the right direction?
Even if I just adjust the outer VisualElement size to, for example, a width of 2496 (the safe area width for iPhone 12 pro max), in the simulator it ends up being WAY too large (about 4x, it seems).
Nevermind, I just found it... it was changing panel setting scale mode to "Constant Pixel Size"
Hello, first time here, I have a question about dictionaries. I understand how to use them in general but how to be specific to game objects I dont quite understand.
In the code I am working on I can spawn a prefab fine, but to remove a game object at a specific key is confusing
This is the code I have been working with, I can remove the index correctly but the object will mot delete properly.
Any ideas?
Send your code in text using discord formatting like
Since you're using an integer for the key and one that's linear, why not simply use a list?
I dont have nitro so sending the code is a bit tough @night harness
How to post !code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
How can I change the parameter in a button event via code? is it even possible
kinda specific test enviorment
Nitro isn't necessary
If the keys are integers and not special.. a list or an array is preferred.
hey?
how to check if Dictinary<string,string> dic 5th item ([5]) has the world "ok" ?
You really shouldn't be evaluating elements relative to order with dictionaries.
With dictionaries, you'd generally have a key and simply acquire the value from the dictionary using said key.
yeah followed it, but they want me to have nitro to send the code anyway
You didn't read the instructions from the bot properly
a powerful website for storing and sharing text and code snippets. completely free and open source.
If you've got like.. 5 to 7 lines of code, inline would be okay. Else consider using an external site to link your large code.
fair enough
What are you trying to destroy here?
Thanks β€οΈ
trying to destroy a rawimage prefab
You want TryGetValue
eg
myDict.TryGetValue(myKey, out myValue)
Destroy(myValue.gameObject)
I don't think you would want to destroy a prefab..
Based on context I'm assuming they mean the instance of it and not the actual file
I'm assuming the dictionary has got instances as values
Most definitely, simply clarifying.
if (!connectedPlayers.ContainsKey(6))
{
connectedPlayers.TryGetValue(6, out myImage);
Destroy(myImage.gameObject);
Debug.Log($"connectedPlayers does not contain 6");
}
something like this, but i get a null ref error on destroy
woild it need to be in a loop?
Well in this case that code only runs if your dictionary doesn't have a "6" key
so myImage will always be null
since the trygetvalue fails
thats a logic problem you need to solve yourself based on what you want from this but in general you can prevent this by putting the trygetvalue in an if statement since it's a bool
true true
do you have any examples for me ? I'm kinda lost on this one tbh
This isn't working and I'm not sure why, https://gdl.space/obedijozit.cpp
Each player is supposed to move with their own keys, but instead they all move at the same time using player 2's keys
@knotty sun Thanks for your support. It appears that when the code runs the first time, the EasyYellowButton is not null, but when the player clicks on the EasyWhiteButton, a new scene loads and for some reason, EasyYellowButton becomes null. Updated code --> https://gdl.space/amexicizoc.cs
Have you heard of Array?
then just drag it to the side
ty
float minDistance = 0f; // Minimum distance
float maxDistance = 100f; // Maximum distance
float currentDistance = 50f; // Current distance
float minLifetime = 2f; // Minimum lifetime
float maxLifetime = 8f; // Maximum lifetime
// Calculate the interpolation factor based on the current distance
float t = Mathf.InverseLerp(minDistance, maxDistance, currentDistance);
// Use the interpolation factor to calculate the lifetime
float lifetime = Mathf.Lerp(minLifetime, maxLifetime, t);
im trying to understand how to use inverselerp to update my position
so if the lerp updates the position i need inverse to lerp to change that to set speed which would be like .01 to 1 and i multiply that for what the default speed would be
InverseLerp returns a 0->1 value based on how far the third value is between the first and second. That's it, use it for whatever you want
any one seen this error before in unity
doesnt seem to be my code but unity specific but i cant press play
Have you restarted Unity?
Howdy friends,
Have this code right here:
void Update()
{
foreach (DetectableData detectableData in detectableDataList)
{
if (detectableData.detectionStateToggle == DetectionState.Increasing)
{
if (Physics.Raycast(detectionEyes.transform.position, detectableData.detectable.transform.position - detectionEyes.transform.position, out RaycastHit hit, Mathf.Infinity, detectionMask, QueryTriggerInteraction.Collide))
if (hit.transform.CompareTag("Detectable"))
{
detectableData.detectable.detector = this; //idk about this one
TryModifyDetectionRate(detectableData, Mathf.Lerp(detectableData.detectionRate, 100 + (detectionRateMultiplier * 10), DetectionCalculation(detectableData) * Time.deltaTime));
if (detectableData.detectable is PlayerDetectable) //this needs to be moved to events
detectingAudioUtility.PlayAudio();
}
}
else if (detectableData.detectionStateToggle == DetectionState.Decreasing)
TryModifyDetectionRate(detectableData, Mathf.Lerp(detectableData.detectionRate, -100, Mathf.InverseLerp(0, 100, detectableData.detectionRate) * Time.deltaTime));
}
}
The problem is that sometimes TryModifyDetectionRate will remove from the detectableDataList which throws an eror since the list was changed during the iteration. The problem problem is that I don't really care that it does this. What's the best way to deal with this error? Should I maybe queue up it's deletion and remove it in lateupdate or something?
oh my lord thats a lot of nested code
it be like that sometimes
it could be a lot cleaner but let me dissect the code to see what the issue is
the column constraints here have heavily messed up the code, making it hard to read. Id recommend doing a quick pass to try and shorten a lot of your lines up to be 80 width at most wherever you can, and then paste into hatebin cuz discord doesnt play nice with lines that are too wide
or do it forward but use a RemoveAtSwapBack function
Id also recommend @night harness you look into Guard Clause pattern, it'll help you reduce your nesting there I expect
but you cant remove in a foreach
Aside from that @night harness I would instead just have your method return an indicator for if the item should be removed, which you store, then after you finish the iterations, you can perform the removals with any notified "these ones need to be removed"
there's also the option of storing all the items in a Queue, and Dequeue/requeue them
and just, neglect to requeue them if you want to "delete" them
thats not necessary just restructure the loop
overall though Id prolly completely modify the way you store the data itself so its not in a list, potentially
detectableData.detectable.detector = this; //idk about this one this looks like a signal it needs to be redesigned from the comment alone π
I'm halfway through the redesign haha
fair enough lol
thank yall for all the suggestions π
ended up with kind of a gross solution using a second list, inspired by @pure cliff's suggestion
if (clearDetectableDataList.Count != 0)
{
if (clearDetectableDataList.Count == detectableDataList.Count)
detectableDataList.Clear();
else
foreach (DetectableData detectableData in clearDetectableDataList)
detectableDataList.Remove(detectableData);
clearDetectableDataList.Clear();
}
if you hold down alt while highlighting, you can avoid copying in all that left padded whitespace
Also, its good practice to scope your if statements even if 1 liners
Saving a couple braces is typically not worth making your code much harder to read and potentially introducing lots of bugs down the road D:
your right but im stubborn π
Also you can do a guard clause at the top
anytime you have
if (condition)
{
logic
}
You can just invert it to be
if (!condition)
{
return/continue/break
}
logic
which reduces a layer of nesting in logic
What's the benefit?
reducing nesting
which makes your code a lot easier to read and maintain
if you have this:
if (conditionA) {
if (conditionB) {
if (conditionC) {
...
}
}
}
Your logic becomes a lot harder to keep track of
i see
Versus:
if (!conditionA) {
return;
}
if (!conditionB) {
return;
}
if (!conditionC) {
return;
}
...
You'll quickly also notice that if there's some kind of typo in your conditions, they are all nice and neatly lined up single file vertically and a typo suddenly sticks out like a sort thumb π
I will keep this in mind, Thanks
i would also move each logic to a function too
https://pastebin.com/aiQpYe2a
the amount of stock isnt decreasing, please help
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.
Oh hey, asked in the other chat, but how are you casting AmmoMaster to int, what does that mean?
I would debug the line after setting held
I'll answer that other question here. Too busy over there:
_inventory[(int)type]
you cast AmmoMaster (which you called type) as an int, to get the index
uuhh
can you show the AmmoMaster class?
wait
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum AmmoMaster: int
{
Magnum,
AR,
Buckshot,
Rockets
}`
AmmoMaster in all of its glory
ah shouldve realized its just an enum
Ah, ok. You don't have to inherit from int by the way
so i can remove the int or do i replace it with something else
in GunInv
should be fine to just remove, but I really wouldnt rely on casting enums to ints in this case. If you add or change the enum ever, all ammo types will be wrong
I mean, you can already cast enum directly as int. I would remove that " : int" part
error CS1031: Type expected
You can hard-code the enums like this:
Magnum = 1,
AR = 2
To slightly make what bawsi said less of an issue
And where is that error?
(erased the int)
from the AmmoMaster class, or the _inventory[(int)type] line?
Assets\Player\Weapons\AmmoMaster.cs(5,24): error CS1031: Type expected
aka public enum AmmoMaster: int
Well you have to get rid of the : as well
ah
But yeah, put some debugs in the code here #archived-code-general message
Check the amount, check held after it's set, and check spend after you run min on it
i come with a question. i'm trying to save a copy of a list into a variable, but i'm having trouble getting that to work.
dialogueScript.stringList = selectedObject.GetComponentInChildren<DialogueInfo>().dialogueOptions;
now this works, but when i clear stringList in another script, it also clears the original list, and i can no longer access it. i reckon i just need to do something like new List<string> but i'm not sure how to properly format it so i can reference dialogueOptions
what would be the proper way to do that?
(full disclosure, i did originally ask this in #π»βcode-beginner but that channel was a little busy with other topics, so i thought it better to delete it and move it here. if that was incorrect, i apologize and won't do it again)
public bool Fire() itself isnt working
GunCore:https://hatebin.com/dzocaltqbq
AmmoInv:https://hatebin.com/insodjwame
first i would definitely split that logic up so arent chaining a bunch of stuff. But you just need to do like
= new List<string>(otherList);
to copy if this is a value type. I assume its a string by the name ah u wrote <string> in there
In that first script I see fire called once, and it's commented out (line 82). Looking at the next script now
lmao nice edit
ctrl F didn't find it in that one. Do you actually call Fire anywhere?
error CS7036: There is no argument given that corresponds to the required formal parameter 'ammo' of 'GunCore.Fire(AmmoInv)'
thats why its commented out
aha that did it, thank you. that's what i wanted to try, but in the parentheses it was asking for the Capacity, and i assumed that to mean i was setting how many spaces there were, not copying the info.
So pass in AmmoInv, what's the issue? You have a reference to it at the top, called ainv
im honestly unsure if you even need to specify the <> if you provide it a list in the parameters. your IDE should tell you if you can exclude it
i guess its the amount?
Not sure what you're saying here
The issue is the amount?
im not sure whats the issue
Assets\Player\Weapons\GunCore.cs(82,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'ammo' of 'GunCore.Fire(AmmoInv)'
Yes, You have to PASS IN the AmmoInv
You just have Fire()
That won't work
because you need to pass in ainv
Fire(ainv)
oh
If a method takes a parameter, you have to give that parameter when you call the method
it works thanks
turns out i do. but regardless, thank you for the guidance.
public struct AmmoEntry
{
// Include name field for editing convenience only - not needed in-game.
#if UNITY_EDITOR
[HideInInspector]
public string name;
#endif
public int maxCapacity;
public int stock;
[SerializeField] public int magazine;
[SerializeField] public int maxMagazine;
//ddd
} ```
why cant magazine be detected?
wdym by "detected"?
if (ainv.magazine > 0) == error CS1061: 'AmmoInv' does not contain a definition for 'magazine' and no accessible extension method 'magazine' accepting a first argument of type 'AmmoInv' could be found (are you missing a using directive or an assembly reference?)
i changed it to if (ainv.AmmoEntry.magazine > 0) now error CS0120: An object reference is required for the non-static field, method, or property 'AmmoInv.AmmoEntry.magazine'
and
error CS0572: 'AmmoEntry': cannot reference a type through an expression; try 'AmmoInv.AmmoEntry' instead
if i use AmmoInv.AmmoEntry, error CS1061 remains
Does your AmmoInv type have an AmmoEntry property/field?
Share the code
you may want to try basic c# courses first. AmmoEntry is a struct, so ainv.AmmoEntry really doesnt make sense.
Your ainv is a AmmoInv
No, it doesn't have it.
It has a definition of the AmmoEntry struct. It doesn't have a property or field of that type.
so i cant call on it in different code?
[System.Serializable]
public struct AmmoEntry
{
// Include name field for editing convenience only - not needed in-game.
#if UNITY_EDITOR
[HideInInspector]
public string name;
#endif
public int maxCapacity;
public int stock;
}
Where is the struct you posted above, because this is in that code you just linked
It simply doesn't have magazine
Not the way you do it. This is really a beginner question. I suggest doing what bawsi recommended.
AmmoEntry is a struct type. You should be trying to access a member variable rather than a type.
oh not yet updated
public struct Example
{
public int a;
}
public Example ex;``````cs
myClass.ex.a = 5;```
You should take this course. Between this and not knowing how to add a parameter to a method, it's clear you need to understand the foundations a bit better
https://www.w3schools.com/cs/index.php
Not cs myClass.Example.a = 5;//Error!
can i ask a visual studio question
Code related?
Did you read the big header that mentions this channel is for general coding concepts in unity? π
You should ask those questions here π , considering it's in no way related to Unity
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
hey guys, i've made an asset menu, and all of the fields show up in the inspector, except one, its public, so idk why it doesn't show up. this is the code for the asset menu https://sourceb.in/G2bjvjjEKv
(there should be a noiseSettings field)
is NoiseSettings marked as serializable
Might want to see if the serializeable attribute https://docs.unity3d.com/ScriptReference/Serializable.html suits you
thanks!
Unity's dumb BinarySerializer strikes again
how to stop JSON UTILITY from making vector3s look like this
im already rounding the value before
my correction it probably makes all floats look like this
How are you rounding the values? Can you show the implementation?
possibly
store as rounded string then convert on load
round it when you read it
use newtonsoft
position = new Vector3((float)Math.Round(p.x, 2), (float)Math.Round(p.y, 2), (float)Math.Round(p.z, 2)),
By not using JSON Utility
It's trash
You can migrate to newtonsoft very easily and it will work a million times better
i see
Only the Vector3 and other math related types will not work properly because Unity has not put any effort into supporting it, but you can add a custom type converter that fixes this
If you are going to migrate, then I can look for a solution if you want, or just write one myself
no need i can find it on my own thanks
Right
Either way, you can't fix your issue as far as I know. This is JSON Utility serializing your Vector3
Please read #854851968446365696 -> Asking Questions
Right now we can't help you because we have no idea what you actually tried code wise
Hello
I am having troubling with serialization on different platforms. The object I am serializing is basic (shown below). I am serializing it with JsonConvert.SerializeObject.
In the editor, this works prefectly. But on Android and WebGL, the serialization results in an empty object {}.
I am using Unity 2020.2.3f1.
Additionally, I tried attaching the visual studio debugger and inspecting the object. It worked as expected in the editor. But on android, it says "children could not be evaluated".
[Serializable]
public class Log : BaseRequest
{
[JsonProperty]
public long time { get; private set; }
[JsonProperty]
public string token { get; private set; }
[JsonProperty]
public string type { get; private set; }
[JsonProperty]
public string data { get; private set; }
public Log(IUser user, string type, string data) {
this.time = DeploymentEnvironment.UnixTime;
this.token = user.Token;
this.type = type;
this.data = data;
}
[JsonConstructor]
public Log(long time, string token, string type, string data) {
this.time = time;
this.token = token;
this.type = type;
this.data = data;
}
}
Using JSONUtility?
Very confused because it does not look like JSONUtility but Newtosoft does not throw silent errors like that
So you must have an error
I want to make an item go around the player and point towards the cursor, what would the best way to do that be
using Newtonsoft
I'm losing my fucking mind.
https://hatebin.com/fklyqrltaa
Here's my code. I've put the Gnome script on a completely fresh new empty object.
I spawned a default 3d cube right above it.
It does not detect a hit, ever. I can put the cube above, i can put the cube right on the empty, it does nothing.
But for some reason, when I switch the cube's collider to trigger, it suddenly catches it (this was sometimes the case even without the QueryTriggerInteraction.Collide), but even if i switch the trigger back off, or move the cube away, it still continues outputing "HIT" to the console and RaycastHit still returns the cube.
just checked another thing and it seems to fix itself whenever i put 2 colliders in its path?????
I must've missed something
Adding a ToString override fixed this but I don't get why, so it's probably something else I missed
I would just step through with the debugger, although I do notice you define a layermask and seemingly dont use it in the method
There's nothing to step through, the Physics.Raycast just does not hit.
Yes, I switched the layermask to -1, just in case that was the cause of the problem
Is -1 some special value to indicate all layers?
-1 is 0xFFFFFFFF=enable all layers....
Ah true
It seems to bug out whenever I start the scene.
Started the scene, moved the cube over the raycast - nothing. Turned off the collider, turned it on - now it works. Feels like something isn't updated properly on the Physics end
Have you ever changed any of the physics settings?
Nope, never. Unless my colleague did, but dont think they would
Can you share a screenshot of the hierarchy and the object with the script inspector?
It's fixed now, I think it might've been the fact that i was using Update instead of FixedUpdate
Hmm
I have a problem with not all UnityEvent hooked up callbacks get called, when I call event.Invoke(); The first one always does, but I now have multiple callbacks (on the same gameobject, but different monobehaviours) the second one gets called pretty much on every other run. Is there a common reason for a callback to be ignored?
No such reason. You must be doing something wrong or making wrong conclusions.
nvm i had to turn on readwrite
@waxen phoenix I can see one difference between your code and mine: you don't set subMeshIndex on your combined instances.
it works now but thanks ill check it
@waxen phoenix I don't know if it's important to you, I'm combining meshes from an asset that shares materials among models so I group them so the combined submeshes use the same materials.
If an exception occur, the next callback will not be called. (I believe)
No errors in the console. I ended up adding the second callback as a DOTween callback, so I only have one handler on my unityevent, cause I do have deadlines on this... but next time I need 2 callbacks I'm going to try to debug what exactly is going wrong.
Inventory System as ScriptableObjects? What if I have hundreds of NPCs with all of them having 10+ items? Makes sense to keep using SOs?
No. Do not make an inventory system as SO.
Think of SO as immutable data.
So should I just use Serializable base class?
Yes.
alright that's what i was doing
The item can be SO though. (The part that is immutable like name, description, icon)
alright
what if i have changeable values like durability that inherit the SO item class?
Durability shouldnt be on the SO.
You have a SO that is the concept of the item. (Name, Description, Max Durability, Strength, Agility, etc.)
You also have a class that represent the current item. (Durability, IsEquipped, etc)
so I'm guessing the current item HAS an SO attached instead of inheriting it?
#π²βui-ux this is not a programming question
I apologize
someone can tell why I always spawn uder world (sory for my bad english)
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh sory
someone can tell why I always spawn uder world (sory for my bad english) https://gdl.space/raw/ovajatidol
The Player transform is spawning underneath the terrain? Or does it have a child object that is translated lower and only looks like it spawned lower than the terrain height? Also, you rewrite the height formula twice, but it's very intricate, so I would recommend creating a method for it:
float GetHeight(float x) => Mathf.PerlinNoise((x + seed) * terrainFreq, seed * terrainFreq) * heightMultiplier + heightAddition;
Hello,
I'm making a 2D game and attempting to have an enemy follow me however it flies through the air instead of sticking to the ground when following. Is there a way I can keep it on the ground without using Raycasts or is Raycasting the only option?
raycasting would be a way to detect obstacles and/or the ground. Not a way to actually do the movement
In general there are many ways to solve any given problem. I would probably have a physics-based character controller for the enemy and a separate AI script to drive it.
Does anyone know what could cause rigidbodies to not move after doing rigidbody.position = ...? The rigidbody is on RigidbodyInterpolation.Extrapolate and CollisionDetectionMode.ContinuousSpeculative and also kinematic. I know, I know, this is probably not much to go off of, but I haven't been able to gather much more info myself either since it seems to be happening very rarely, most likely because update and fixedupdate have to be called in a specific order for this to occur. Basically I want to know if anyone has had or knows possible problems that could be the case for me. If I manage to get it to happen whilst debugging and get some more important information I'll let you know.
Can anyone explain why this is happening with my third person RB controller?
Here's my code: https://hatebin.com/ujoyfgzllc
Maybe try to lock rotation on some axis?
Already tried that...
oh also !code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oops
Hi all I am getting a mismatch error after I instantiate the sectorGameObject sector is the scriptable object I have a prefab gameobject in.
can anyone help please?
You get an error?
nope no error in the inspector just my scriptable object. ill show you before and after
hold on so what is not working
before and after
everytime i restart the game i have to re-assign the gameobject in the scriptable object
found the issue! it was just an operator typo
Assets cannot reference objects in scenes at edit time
that reference is only going to be valid at playtime / until a domain reload
ok but i should not have to keep re-poplating my scriptable objects everytime time cause when i stop to restart i then get a null ref error because the object has now been removed.
when I am instantiating from the scriptable object something is causing to be removed from the scriptable object. this is what I am trying to fix.
I explained the oissue
it is not possible for assets such as prefabs and SOs to reference scene objects except at runtime
What could be the reason my parent Gameobject change values for transform position in the start of the game ? As result my level is asynchron.
Image1: parent
Image2: chield
Image3: parent while play
This issue does not occur if there is no child.
The Rigidbody is colliding with something and depenetrating
When I have a ScriptableObject with an "AudioSource" property, it is not possible to drag an drop an object from a prefab inside this property in the inspector.
Is this generally not something you'd want to do anyway or is there a way to achieve this.
from a prefab you can
from the scen you can't
I got an Abstract class that has 3 or actually more functions which is some of them private, some of them public. I will use that same Abstract class's methods for Monobehaviour either ScriptableObject. But i couldnt solve it since it accepts only one base class. Example:
`public abstract class X: ScriptableObject
{
public abstract IEnumerator MethodIEnumRequired();
private protected abstract void MethodPrivateRequired();
public abstract void MethodPublicRequired();
}
// Fine for ScriptableObject's
public class AScriptableObject : X {
}
// Error here. Cant define multiple Base class
public class AMonoBehaviour : MonoBehaviour, X {
}`
I dont want to define second abstract class or it is my actually last chance. I need only one Base class. I was trying to solve this like tomorrow but my knowledge is not enough or maybe it is not possible.
I cant use Interface's or maybe i can i dont know.
Class X will have some shared Private/Public Fields too.
Its indeed impossible. We need two seperate abstract class for each and one Interface to keep Public methods required.
How to overlap check with mesh colliders ? (the dumbed down ones)
Hi, I made a big complex change to my Game (added a entire new System), now I noticed, that everything is pretty laggie. I have around 40 fps right now, which was around 90 to 120 before. Is there a way to chace down the issue of the performance issues? Like, is there a way to see which code / script is the cause of the perfomance issue?
hmm but im trying from a prefab
I double click the prefab, and drag the object which has the audiosource as the component on top of the audisource property from the scriptable object
Profiler window
but as far as I see there is not exact list of which script takes how to long to be executed. Is there a way to display the data like that?
why cant i use velocity on a rigidbody kinematic while its working fine on rigidbody2d kinematic ? Does exist any workaround ?
What do you mean by "use velocity"? The docs say If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.
ScriptableObjects can't have AudioSources attached
so it's unclear what you're actually trying here
I think what I'm trying doesn't make sense
it doesn't make sense to reference a component of something that only exists during runtime in a scriptable object, only things that exists before
correct?
yes
yeah, ok, I'm still trying to understand SOs, currently switching a lot of things over and really enjoying working with them
thanks
Check out Deep Profiling
ohh, thank you
You need to really zoom in on the main thread window to see the blue parts
thx, already got it. The issue was that the code somehow executed the part of the worldgeneration two times (so every gameobject was placed two times)
yes but rigidbody2d.velocity works fine with kinematic, for rigidbody i need to look for an alternative like moveposition which i dont like because i need fixedupdate
i have a randomized spawner that Instantiates another spawner that Instantiates a coin, when the coin is collected it calls a function that spawns another coin, the function is in the spawner that Instantiates coins, when i run the game the coins only get Instantiate in the original coin spawner, but is it possible to call the clone of the coin spawner? diagram to expaline it better
this is some next level inception design... but, yes, you can. Give your spawner a method (i usually name mine Initialize()) and pass a reference to the original, and track that reference.. ie:
public class OgSpawner : MonoBehaviour
{
public void SpawnRandomNewSpawner()
{
NewSpawner ns = Instantiate(...);
ns.Initialize(this);
}
public void DoSomethingLater() { ... }
}
public class NewSpawner : MonoBehaviour
{
private OgSpawner _originalSpawner;
public void Initialize(OgSpawner originalSpawner) => _originalSpawner = originalSpawner;
public void OnCoinCollected()
{
_originalSpawner.DoSomethingLater();
}
}
alr ty, ill try to figure smth out
I have a chest object that appears in every room of the map where, once the player touches its trigger, it enables two buttons and sets these buttons to different cards. The player can choose one of the two cards to keep and the other gets discarded. The issue I have is, how do I get the buttons to always reference the current room's chest on it's OnClick() method?
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine;
public class CollectCard : MonoBehaviour
{
public AudioClip cardCollectAudio;
AudioSource source;
public List<CardEffect> lightCardPool = new List<CardEffect>();
public List<CardEffect> darkCardPool = new List<CardEffect>();
public CardEffect thisLightCard, thisDarkCard;
public Button lightButton, darkButton;
GameObject player;
void Start()
{
source = GameObject.FindWithTag("GameManager").GetComponent<AudioSource>();
player = GameObject.FindWithTag("Player");
thisLightCard = lightCardPool[Random.Range(0, lightCardPool.Count)];
thisDarkCard = darkCardPool[Random.Range(0, darkCardPool.Count)];
lightButton = GameObject.Find("Canvas/Cards/LightCard").GetComponent<Button>();
darkButton = GameObject.Find("Canvas/Cards/DarkCard").GetComponent<Button>();
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.CompareTag("Player"))
{
SetupChoice();
}
}
void SetupChoice()
{
lightButton.transform.parent.gameObject.SetActive(true);
}
public void OnCardChose(CardEffect chosenCard)
{
lightButton.transform.parent.gameObject.SetActive(false);
source.PlayOneShot(cardCollectAudio);
chosenCard.ApplyEffect(player);
Destroy(gameObject);
}
}
Why isn't OnTriggerEnter2D() working on the "shot" prefab(collider and rigidbody attached in 1st pic)? I've made fully sure it's colliding with the object(collider and rigidbody attached in 2nd pic) but still it's not working. I've searched a lot but found no solutions.
Personally (hot take incoming), I'd use a singleton class with static methods that you could call from anywhere - something like PlayerDeckManager.AddCard(CardEffect newCard). Alternatively, you can initialize your CollectCard with a pointer to whatever holds the deck. Kind of like my message above, actually, with the spawner question.
What's lerping in unity?
ok different question, how would I set the variable of a button's OnClick()
that
you can pass a parameter (which is a little sloppy in my opinion, but many people do it this way)
how would I do this
try adding (int parameter) to OnCardChoseRelay()
better is probably setting whatever type of card is when you instantiate it, so the button "already knows" what type it is and just.. adds the correct card or whatever to the deck
also dont' crosspost
Ye thats what i wanna do. When the chest is enabled, I want the two CardEffects that have been randomly chosen to be set as the variables of the OnCardChoseRelay()
But i dont understand how i set that variable
so read this βοΈ
After you instantiate the card, set it with an initialize (or whatever you want to call it) method
public void OnPlayerOpenedChest()
{
CardEffect left = Instantiate(CardEffectPrefab);
left.SetCardType( /* random type for left card */ );
CardEffect right = Instantiate(CardEffectPrefab);
right.SetCardType( /* random type for right card */ );
}
public class CardEffect
{
private CardEffectType _type;
public void SetCardType(CardEffectType type) => _type = type;
public void OnClicked()
{
// add _type to the player's deck/collection
}
}
I have a question
would this work as a substitute
{
lightButton.transform.parent.gameObject.SetActive(true);
lightButton.onClick.RemoveAllListeners();
lightButton.onClick.AddListener(() => OnCardChose(thisLightCard));
}```
something like that
sure
alr thanks
how would I get a reference to the buttons if they are inactive when the Start() function of the chest is called?
as I can't use the transform.Find("") function
Are you Instantiate()-ing them? Or do they already exist in your scene
If you're using Instantiate() to create a new button, then keep a reference to it:
CardEffect newCardEffect = Instantiate(CardEffectPrefab, ...);
// now do something with newCardEffect - call a method on it that tells it what kind of button it is, for example:
newCardEffect.Initialize(CardEffectPoison);
If you have them in your scene, then create a script and variables to track them:
public class CardScene : MonoBehaviour
{
public CardEffect leftButton;
public CardEffect rightButton;
}
and do the same - initialize them when you "create" them (or show them)
you can still reference items that are inactive
not with the Find() function
the descriptions i just gave you make it so you don't need Find
which you shouldn't be using anyway
why not?
because it's [very] slow, and you should learn how to track references to things anyway.. if you fill up your game with Find() you're gonna find (ha) pretty soon your game's performance is terrible
doing it once or twice is fine, but realize that in order for find to work, it has to traverse the entire object tree - literally every single object and component in your game
what about FindWithTag()
i mean, sure, but I don't really understand why you aren't just doing it yourself - you already know the reference to the object, you don't have to find it
for some reason you're selecting to do it in a way that's neither simpler nor better π
Because the chest and its parent are prefabs
so?
So i gotta reference it in the chest
because a prefab can't retain a non-prefab variable
yes...... and I've posted how you do it like.. 3 times π Show me the code and I'll literally write it out
of course it can
not in the asset folder
sigh
Yes, it absolutely can, you just need to do it - like I've described above a bunch of times. π Show me the code for your prefabs
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine;
public class CollectCard : MonoBehaviour
{
public AudioClip cardCollectAudio;
AudioSource source;
public List<CardEffect> lightCardPool = new List<CardEffect>();
public List<CardEffect> darkCardPool = new List<CardEffect>();
public CardEffect thisLightCard, thisDarkCard;
GameObject cardsParent;
public Button lightButton, darkButton;
GameObject player;
GameObject gameManager;
void Start()
{
gameManager = GameObject.FindWithTag("GameManager");
source = gameManager.GetComponent<AudioSource>();
player = GameObject.FindWithTag("Player");
thisLightCard = lightCardPool[Random.Range(0, lightCardPool.Count)];
thisDarkCard = darkCardPool[Random.Range(0, darkCardPool.Count)];
lightButton = gameManager.GetComponent<RoomManager>().lightButton;
darkButton = gameManager.GetComponent<RoomManager>().darkButton;
cardsParent = lightButton.transform.parent.gameObject;
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.CompareTag("Player"))
{
SetupChoice();
}
}
void SetupChoice()
{
cardsParent.SetActive(true);
lightButton.onClick.RemoveAllListeners();
lightButton.onClick.AddListener(() => OnCardChose(thisLightCard));
darkButton.onClick.RemoveAllListeners();
darkButton.onClick.AddListener(() => OnCardChose(thisDarkCard));
}
public void OnCardChose(CardEffect chosenCard)
{
source.PlayOneShot(cardCollectAudio);
chosenCard.ApplyEffect(player);
lightButton.transform.parent.gameObject.SetActive(false);
Destroy(gameObject);
}
}
this is the current code I have written
havent tested yet
the gameManager stores the buttons and the chest finds it and gets the variables as references.
and what's this for? one instance of a "collect card"? ie, when you have a chest, there are two of these that pop up?
Yes
I believe so
When you collide with the trigger, two buttons are enabled and you choose one of the two
I'm confused - is this a "chest" (ie, is there one of these?)
and there's 2 CardEffects?
Hi, I've done the setup in #854851968446365696 , but my vscode still doesn't give me suggestions for things from outside of the current file - how can I fix it? I'm on linux, endevourOS
And since you're not instantiating the CardEffects, I'm assuming you've dragged your prefab into the scene (twice) and linked it to this CollectCard?
and in the corner, processing workspace information in background spins endlessly
The CardEffect is a scriptable object
@indigo arrow show me CardEffect.cs
how are you rendering the card effect buttons? is it just literally a Button?
using System.Collections.Generic;
using UnityEngine;
public abstract class CardEffect : ScriptableObject
{
//public abstract string cardName;
public abstract void ApplyEffect(GameObject target);
}
yes
with an image
fine, and so what's the problem again? pressing the button has no effect?
what all should I have broken off into other files in yalls opinion...this is my Loadout Managers functions and its over 1000lines :/
Im thinking the popup ones should have been in other file
not sure what all else
ive fixed my issue
You have a mess of code here - popups should take care of themselves, items should take care of themselves, navigation should all be in the same place, etc
It works perfectly fine now
the issue was that at first, I didn't know how to add a listener
this is all UI main menu loadout btw
so items shouldn't do that part imo?
and after that, I didn't know how I would reference an inactive button
What's a "Loadout"? Like, which items are equipped in which slots?
yeah, something like this
LoadoutManager is basically in charge or everything you see here
items, buttons, equiping items things like that
So like, you have tonnnnnnns of logic crammed in here. Your mental model of what a component is should be smaller - typically (well, for me anyway) you only orchestrate conversations between components at the smallest possible level
So like, your items in your inventory - these should be something like ItemRenderer or ItemIcon that has all the logic for what item to draw, what the text is, what the rarity color is, etc
it should also be able to handle it's own drag & drop - if you need to orchestrate it at the parent, you implement the mouse down/up/click/drag at in the icon component, then have the parent orchestrate.. am I making sense? lemme maybe stub out some code
gotcha...this is UI toolkit so some of the stuff is a little wacky also π
so basically split into the 3 main categories you see...the left sidebar, the middle part and then the right side inventory part?
and from there have the right side items do their logic/rendering and from the middle maybe breakout code for heroinfo/hero upgrades button
(I at least broke the hero info/her upgrades into another file...which is also like 500lines now lol)
public class ItemIcon : MonoBehaviour, IPointerDownHandler, IPointerDragHandler, ... etc
{
private LoadoutScreen _loadoutScreen;
public void Initialize(LoadoutScreen loadoutScreen) => _loadoutScreen = loadoutScreen; // and whatever info you need to render an item
public void OnDragEndHandler(...)
{
_loadoutScreen.ItemDropped(eventArgs.position);
}
}
public class LoadoutScreen : MonoBehaviour
{
public InventoryPanel inventoryPanel;
public LoadoutPanel loadoutPanel;
public void InitializeInventory()
{
foreach (GameItem item in Player.Inventory.Items)
{
ItemIcon itemIcon = Instantiate(ItemIconPrefab, InventoryContainer.transform);
itemIcon.Initialize(this);
}
}
public void ItemDropped(Vector2 position) // and item type, or whatever
{
// check if it's on the loadout, if it's a valid item, etc, if so, remove it from inventory and add it to the loadout
}
}
something like that - LoadoutScreen only handles orchestration between the panels, but the panels/icons render themselves and have all the logic related to .. just the smallest piece of UI you possibly can
so for each "button" like hero-info and merge and hero upgrades...you would split those into their own classes/files?
the ItemIcon in my example above tells the "parent" (LoadoutScreen, in this example) that it's been dropped on some location. LoadoutScreen tells the "LoadoutPanel" that it's been dropped, maybe it has some logic to check if it's a valid drop, and if not, tell the icon to "go back to the start drag location")
very much so
gotcha...do they all need to be in their own file? or just own class
in my bigger project, my "renderers" are quite numerous
I'd put them in their own class and even nest them by functional area
but this makes the design of your app simple - if you need a draggable icon of some sort (like, in your inventory, loadout, maybe in a chest popup dialog showing what's in the chest, maybe on the store page, etc) you only need to write that script and code once
and every place that "holds" it just says "ok create an icon of type Iron Chest Armor" and away you go
do you like "write out" what each code should have and how many files to create beforehand?
or do you kind of just jump into coding π
i've been doing it long enough that i just sorta know what needs to be created, and I have my own library of stuff that i reuse
but in general, the smaller your "thing" is, the better
like, for example, in our game we have resource icons - gems, credits, green gel, and "aurite".. i have a resource icon that I can use eevvvvvvvvvverywhere without needing to write logic to show 1 of 4 images based on the type
it's really a simple "renderer":
but anyplace I need one of these, i just instantiate one and call Initialize(ResourceType) on it and it draws itself
Another small example but more "pure" - I use sliders everywhere in my games, and wanted to make a few features on them that the default unity sliders don't have - a gradient for texture color and text color, and animation.. so .. I have a class that does all these, and I can just add this prefab to any other object that has a slider and it "just works" without needing any scripting.
Also I hated always writing slider.value = (float)currentValueInt / maxValueInt; so I also just wrote that line of code once in my slider with a different API: slider.SetPercent(currentValueInt, maxValueInt) which does things like always convert it to a float, clamp it to 0-1, etc.
So as you go in your game dev, you just build your own library of components (reusable or otherwise) so your source code is small and you don't end up with 1000 line files
Nothing wrong for having 1000 lines of code π
whats source code?
your code
this is speaking to me. make components editable so you don't have to go back and redo everything over and over
looks at TMP code
8000 lines in 1 file
8000 lines in 1 file...... π
If you were on my team you'd have a "do this right now" task related to that.. π
does it count if the file is auto generated :x
Ive seen some pretty nasty big stuff generated by automated mechanisms that have no qualms about just casually plunking a several ten thousand line long balrog into the source o_O
but we dont check that into git since it generates on compile wheeee
Yeah, unfortunately mine has to be in git because we build from git and android needs AOT
How would I overried an abstract sprite:
{
public abstract Sprite cardSprite {get; set;}
public abstract void ApplyEffect(GameObject target);
}```
With another sprite in a subclass:
```[CreateAssetMenu(menuName = "Powerups/Damage")]
public class DamageCard : CardEffect
{
public float damageMultiplier;
public Sprite damageSprite;
public override void ApplyEffect(GameObject target)
{
target.GetComponent<PlayerShooting>().bulletDamage *= damageMultiplier;
}
}```
And then be able to access it in another script:
```Sprite thisCardSprite = chosenCard.cardSprite```
Does anyone know why vscode might still not show code suggestions, after doing all the setup in #854851968446365696 ?
I write Time. and it doesn't suggest anything like deltatime
I write GameO and it doesn't suggest GameObject
it only shows suggestions from System libraries
same way you overrided ApplyEffect, your IDE should even be saying you have to do it because you declared it as abstract which means the sub class has to implement it in some manner
public override Sprite { ... }
theres a good three different ways to declare properties, but its the same as usual for a property, you just have to put override in its declaration, like what I wrote above
usually having set; exposed on an abstract property is a bit of a code smell though, if its abstract typically its get; only unless you are doing some fancy stuff with the getter/setter on purpose
im just tryna make it so that i can drag in a Sprite into the variable, and then it overrides it and i can access it through a different script
make it a full property backed by a private serialized field
can just put this on the parent class and call it a day
[SerializeField] private VarType _myVariable;
public VarType MyVariable => _myVariable;
What whatever you drag and drop onto _myVariable in the inspector will be exposed (readonly) through the property (but cant be set, only get)
if you're using default get; set; functions instead of fancy implementations, you can do [field:SerializeField] like this:
[field: SerializeField]
protected float _something
{
get;
private set;
}
and it should work
by fancy implementations I mean even something like
get
{
return somethingElse;
}
it won't work then
I would, when using an abstract base class, go with the assumption that there may be need for a fancy implementation downstream, so I'd even go so far as to declare it as public virtual to enable overriding capability.
otherwise it can be a bit of a pain to undo the above and convert it over if you've tightly bound your stuff together, and renaming/changing the field/prop can even deref the stuff in the inspector so now you gotta go and do a bunch of drag and drops again D:
I need some help with this... I've been trying to fix it for a while now but I have no idea what might be the issue.
I basically have a worm enemy with several body segments and a tail, which are supposed to follow the head, so I save the head's last position and rotation in a queue and then just update the worm segments to the head's previous positions & rotations (the head's movement itself takes place in a coroutine, so probably somewhere between Update and LateUpdate)
For some reason if you focus well enough you can notice some weird "snapping" going on with the body segments, as if they lagged behind and shortly after snapped back into place. Usually it's negligible, but sometimes this snapping if fairly visible and I don't know how to stop it
(It's mostly visible here when the worm is moving on top, from left to right, after the first loop - after 0:06)
I haven't been able to find anything online, in beginner, general, or the input system. I'm trying to get local coop to work with 2 xbox controllers specifically. I have each controller moving their respective player but only one controller is able to send input at a time. So if I hold fire on both controllers only the one that was pressed first will work. Any idea of there's a setting or something that needs to be done to be able to accept the input from both controllers simultaneously?
Answered in #archived-code-advanced, though really an #π±οΈβinput-system question ^
not quite
Does anyone know if SphereCastAll returns results sorted by distance? Or just randomly
unity docs don't seem to have an answer
nevermind, the SphereCastNonAlloc does have an answer, it's random
Anyone happen to know a way to get the normals of two connected line segments on a polygon collider 2D, or even a way to get the normal at corners?
The order of all of them can pretty much be considered random, although if you figure out what they do internally maybe you can get a true answer π
what do you mean by "the normal of two line segments"?
Hello does someone know how to code this effect for an int or a float ?
float targetValue;
float displayedValue;
void Update() {
displayedValue = Mathf.MoveTowards(displayedValue, targetValue, Time.deltaTime * speed);
}```
For example with a health bar the displayed value is before damages et the target value is after damages ?
sure
target value is the "actual" value
How could I go about using ComputePenetration to get a trigger to behave like a non-trigger collider?
Right now I am attempting this by first using a Physics.OverlapBox() that uses the collider's bounds extents and its position to get nearby colliders.
I am then getting the direction and distance of the penetration using Physics.ComputePenetration() (I am filtering to focus on the deepest penetration)
I am then getting the "Contact point" by using Physics.ClosestPoint() in the inverse direction of the "direction" output of ComputePenetration.
From there I am attempting to apply a force at the contact point but I am having a few issues.
The box rests slightly within the collision surface.
The box when rotated will very painfully slowly roll to correct itself, but overcorrect and roll-oscillate infinitely.
I also am not sure about how to go about friction.
I guess I should also mention, I am at the moment attempting this all by adding forces to a rigidbody,
There must be an easier way. What are you trying to accomplish, and why can't you use two colliders, a trigger and a non-trigger?
im trying to handle collision manually so I have access to friction forces and force transfer between bodies
But why can't you use a normal collider?
because I dont have access to those things with a normal collider
I'm still not sure I understand. To what do you need access, that a normal collider doesn't have? What's your actual usecase?
There's usually no point in recreating the entire physics collision system. There's an easier way for sure
well, Im trying to make a wheel collider that uses a mesh without bouncing around like crazy so I need to
1 : apply a dampened collision force to prevent inconsistent acceleration
2 : calculate and retreive friction forces for good torque application
3 : accomodate the suspension hitting its bounds (any collision force not absorbed by the wheel should go to the Body)
It seems easier to try and calculate those using collision data, as well as the parameters of the physics materials of each object that partakes in the collision, have you already tried that approach? Recreating the physics system seems like an overkill
I originally tried using jointed rigidbodies, which ended up being a wobbly mess. Ive considered retrying with articulation bodies but I remember those not having a very good angular velocity tolerance and I also would still like to get my hands on all the friction data
Depending on your situation, you might either want to use this asset https://assetstore.unity.com/packages/tools/physics/nwh-vehicle-physics-2-166252 or figure out how they're doing the things. They seem to have something that you need
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerCameraController : MonoBehaviour
{
public float Sensitivity = 70f;
public float RotationSmoothing = 0.1f;
private InputAction LookAction;
private Vector2 LookDirection;
public Transform playerBody;
private float xRotation = 0f;
private float yRotation = 0f;
private float xRotationVelocity = 0f;
private float yRotationVelocity = 0f;
private void Awake()
{
LookAction = new InputAction("Look", binding: "<Mouse>/delta");
}
private void OnEnable()
{
LookAction.Enable();
}
private void OnDisable()
{
LookAction.Disable();
}
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
LookDirection = LookAction.ReadValue<Vector2>();
float mouseX = LookDirection.x * Sensitivity * Time.deltaTime;
float mouseY = LookDirection.y * Sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
float smoothXRotation = Mathf.SmoothDampAngle(transform.localRotation.eulerAngles.x, xRotation, ref xRotationVelocity, RotationSmoothing);
float smoothYRotation = Mathf.SmoothDampAngle(playerBody.rotation.eulerAngles.y, yRotation, ref yRotationVelocity, RotationSmoothing);
transform.localRotation = Quaternion.Euler(smoothXRotation, 0f, 0f);
playerBody.rotation = Quaternion.Euler(0f, smoothYRotation, 0f);
}
}``` in this code, does anybody see any obvious reason why at random times the camera will just jolt across the screen at mach 10
it's confusing me
don't multiply mouse input by delta time, mouse input is already frame rate independent and anyone teaching otherwise is wrong. when you remove that make sure to lower your mouse sensitivity variable both in the script and the inspector
also obligatory "use cinemachine"
It's probably happening around specific angle values, have you checked how they change when this problem happens? Maybe a minus suddenly turns into a plus, or something like that. Happened to me a couple of times
also, whilst im here, is there a good way to check if the game window has focus, when i do Application.isFocusedit doesn't do anything really
Is it always true or always false?
neither, it changes but only when unity itself is in focus
im going for more play in editor in focus
like actual game window in focus
Oh yea that's how it's gonna go - it will work properly inside a build
ohhhhhhhhh
alright
thank you
removing that delta time thing worked for the random jolts
so that's great
That said, as a workaround, you could check if the mouse position is outside the rendered screen.
now i have to make the character feel like its not just floating 
it looks ridiculous
I am still thinking about this π
#archived-code-general message
Interfaces
What about private methods?
Make them protected
Not accepted in interface
should i do jump on press or release, what do you guys think?
And if they're virtual, you can provide an implementation I think
or should i make it a setting that you can chose your preference in a GUI
Press, I think, unless release really works better for your game. Press feels faster
An interface is just a contract that states any implementator of this interface will provide these objects. C# doesn't support multiple inheritance so your options are to use interfaces, or make your abstract class implement monobehaviour
idk, personally im an unreal engine teacher so im trying to re-create the default character movement from unreal in unity
im used to it
also, question is there a way to make the public members be in categories
Either a custom inspector, or something like Odin, I think
Orr just put them in a [Serializable] struct
use the Header attribute
That will work as a good separator, but won't be a complete box, you might also want to use [Space] if you want separation with no text
for the struct i need to use C# 10, now do i change which version im using in unity
wait i can google that
Wait what? You don't
For the struct? Yea unfortunately
Unless you can make a constructor for it
Or a MyStruct.default with default values, something like Vector3.zero
And you can just assign it in code when declaring the variable
https://forum.unity.com/threads/unity-future-net-development-status.1092205/
This is the development status for updating .net
Idk about constructors, haven't used them in c# yet lmao
And a blog
Is unity 2021 uses c# 8? or 9?
2021.1 is C# 8, 2021.2+ is C# 9.
If you have .NET 4.x selected in your project settings, yes.
If you're on 2021.2+, you can use C# 9 in either API compatibility level. Although .NET Framework 4.7.1 would normally be limited to C# 7.2, Unity's compiler bypasses that.
It seems i missed some things while configuring unity
So in you, there is a 4.x?
It used to be called that, I think they just renamed it to .NET Framework.
Oke i will try
if you don't have a reason to switch from .net standard to .net framework, then don't
I need the new interface implementation thing idk if its compitable with unity
**Ref: **https://stackoverflow.com/a/69142418/20905578
is it?
You haven't said specifically what version you're using.
But why you said that? There is performance issues?
I dont know it says 4.7.2 π
Which Unity version.
2021.3.18f1
Then yes, you can use default interface methods.
it has to have a body to be private
But interface
yes, you cannot have a private method on an interface unless it is a default implementation
I thought it would act like a contract
But this
Oh
So i need a default implementation
Okey let me do it
It is an error for a private or sealed function member of an interface to have no body.
why do you even need a private method on an interface anyway if it isn't for a default interface method?
For this sir: #archived-code-general message
I cant use multiple classes in one class. If i use interfaces, it will be easy
I dont understand how it works with interface right now
interfaces are not a substitute for inheritance and should not be used in that way
interfaces are a contract that an object will implement specific public members to be accessed from other objects. a private member cannot be accessed from other objects so you shouldn't have them on your interface except for the case of a default interface method, which is really only useful for some very specific instances
So i will need 2 abstract classes with same codes π₯Ή
why do you need both a monobehaviour and a scriptable object with the same private fields and methods?
I am using Addressables system to manage my assets in memory. But my project wont Load Handle's all the time. So i made something for that and it acts like a "Loader&Unloader". But the loaded object could be a ScriptableObject or MonoBehaviour. So same implementation is needed. Or actually i could do Singleton or even Event system. But this one will be easy to maintain and understand.
But it could be a ScriptableObject or MonoBehaviour.
why
The loaded object will contain some AssetReference's and they handling itself in memory.
i don't really understand why you are trying to do it like this and it sounds like you're coding yourself into a corner tbh π€·ββοΈ
.d yeah i feel that too but getting fun. While i code, i always think the future about the code. What will happen? What will it do? Which things possibly can be added into that code? Maintining part is important for me
Yeah i think thats it. Thank you for helping sir 
He's suggesting you're writing code that is not extensible and he is correct
I highly recommend reading about composition versus inheritance
this would be meaningless to do anyways. Declaring a protected abstract method on an abstract class that isnt consumed by that same abstract class elsewhere is pretty much always a code smell
If you have an abstract method on an abstract class, it should be because that abstract class needs it for something
really sounds like you are overcoplicating things, thinking about future cases that are not concret yet
then with the more abstraction added, its harder to modify things as you go forward
why have a loader and unloader, addressables will return the handles for any load or instantiate operation, you can use those to both wait for completion but also release resources too
can release things during the OnDestroy of the thing that loaded them
i made a custom inspector
you can also do it without a custom inspector as well
i know you can do some of it without one
but not all of it
afaik
you just need to make classes that hold what you want with each group, and mark it Serializable
if not wanting to do that, or a custom editor, i will use the Header and Space attributes to add some orgnization to things as well
i made it easy to use
and i learned something
so
im happy with that
i am 90% sure my code is deplorable
but it works
[SerializeField, Header("Physics")] private float Gravity;
the code 
why did it include visual scripting
huh
not even being used
i find it really funny how the code for the movement component is smaller than the editor tool

welcome to UI code
often happens, also find my unit tests are often larger then the code they test
i like to think im good at making games but the problem for me switching from unreal is the names of everything
i know what things do but i dont know that i know that
because the names are different

thats not a huge problem, some searching and docs can solve that
the concepts and how to solve problems are harder
well C# was one of my first languages
so i know C# pretty well
but i learned C++ and i now teach unreal engine
yeah but a game engine is like a massive library, and you do end up handling a lot of thigns in patterns not common out of games
i decided i'd give unity a shot again, idk why i stopped using it tbf it's alright
unreal engine has too many features
have used both, and in house engines
find unity fights me less when you game design does not aling with how hte engine wants me to work
and as a bonus i dont have to deal with that pesky language we all call C++
always felt unreal is more oppinoiated about how you do things
in unreal there are about 10 ways to do one thing
especially in blueprints
unity is a pain to start off with
but once you've gotten going its much easier imo
unreal gives you everything
This is all very redundant. If you want to make a slider you just add [Range(min, max)] above your field.
If you want to make a foldout, you can just put your fields into a serializable struct.
Generally when making custom editors 90% of things should be using PropertyField so it uses the PropertyDrawer associated with the element and you don't have to manually specify the right type of editor control that can draw the type
which is annoying
it offers less out of the box, but i do find building your own tooling for your games exact use cases is much easier in unity
i'll keep that in mind for the next one
extending the editor in unreal is a pita
yeah also you can easily make a 2D game in unity
unreal engine is soooooooooooooooooooooooooooo bad for 2D games
if you make a 2D game in unreal you're a masochist
i hate unreal's 2D engine
I recently made a graph for how to choose editor extensions and most of it leads to Create a Property Drawer
https://unity.huh.how/programming/editor-extensions/choices
its so bad
but yeah the UI things you did all possible via attributes, and creating classes as containers
unreal's Paper 2D is so deplorable
i cant stand it
and i teach unreal for a living 
im supposed to advocate unreal 
anyways time to sleep
In VScode, when I type three slashes "///", the lines below are automatically generated. How can I disable this so that I can type multiple slashes in a row without this happening? I've tried googling this but all I can find are people trying to MAKE it happen. Thanks.
///
/// </summary>```
Why would you want to disable that?
its a useful feature actually
Why are you using triple comments if you're not writing a summary?
the summarys show up in your auto completion
how do I disable it?
its a way to document functions
It appears when you hover functions
what setting disables this behavior? I don't want any auto completion.
I have no idea, because it's an extremely helpful thing
it has literally never happened until today
why not just draw lines in a different way
// ==========================
Why not just use a different line, like anything in between a multi-line comment /*asdasdasdasdasd*/
the xmldoc feature is really useful for documenting the public api of your stuff
seems pretty common too π
because I'd have to replace 50 lines so that the formatting matches
I can find and replace but I'm used to it this way
I would avoid stubbornly sticking with a format that isn't great
In Visual Studio you can use this plugin to hide detail and leave only preview https://marketplace.visualstudio.com/items?itemName=3dGrabber.NoComment
(Doesn't work in 2022 :( )
Also common
What you're doing is cursed but if you can find someone explaining how to turn it on that should, by extension, teach you how to turn it off
VS Studio has a setting called "generate xml documentation comments for ///". What is the equivelent setting in VScode?
Nobody knows because nobody here would have tried to turn it off
Everyone would be just googling for you
it was off until it wasn't.
So then what'd ya change
I imagine you were just doing it in contexts where it won't autocomplete a summary
either that or it was introduced with the C# Dev Kit package that the VS Code Unity extension was recently updated to
I actually think it was this
seems weird if it was since its not a feature for unity, but a general C# thing
There's a unity for visual studio code extension that gets updated p regularly
this started happening after an update
Im working on a 2d game where you control a 2d rigidbody, this controlling is done inside fixedupdate(). The rigidbody is tracked by a camera with a smooth follow inside of update(). when the camera follow it looks like the player is stuttering because my monitors refresh rate is higher than the rate of the physics loop. Is there a more proper way to do this that avoids this issue?
@warped bane try using LateUpdate instead of Update for the camera follow logic
that doesnt change much, the issue is is that the player is not update often enough, due to it being physics based
then you would need some sort of interpolation over time on the camera
would use something like Vector3.SmoothDamp to move the camera to a target over multiple frames, and a set speed
You can also try setting the rigidbody to Interpolate
I found a solution, i had to set the player rigidbody to interpolate, so that it moves every update instead of physics update
ah yep lol
thanks for the help
I don't think this server is actually very reliable for getting good help
ello lads. i've got some prefab assets that i've combined together and put under an empty parent object. i wanted to know if there was a way to check from one of the child objects if the parent object had another specific child object. the way i'm trying to do it feel very roundabout, and i'd rather ask first before i waste my time with an excessively complex method
some other servers have a thread system, which i think would be way nicer to have here. But those other servers are not as active which is why im asking here instead
i'm doing this from a script that checks for an interaction with one of the child objects, not from a script that is already on the child object.
i tend to drag in the references i would need on the parent object and have it control its child objects, but otherwise the various GetCompoentInParent / GetComponentsInChildern methods should work
You could track this with code, simply using a public bool that you set when you add the object you want to track
You just have to do a better research when answering questions then help will get better.
There's no dedicated helpers here to service threads. This is a community server, anyone who has free time to help volunteeer it.
As stated, a forum would be much better. This server is out of date.
go to the forum then
internet forums are very slow, it can sometimes take hours to get a reaction. thats why forums on discord is so nice
especially with a server this big
It's a community focused on learning. If you want !forums you are welcome to use those.
π¬ Have a question that requires a more detailed explanation? We suggest using the Unity forums https://forum.unity.com/ to ensure your question is answered more effectively.
it's not very active or speedy but it's true, probably way more reliable
https://forum.unity.com/
Trying to get the mouse position but because I'm using a canvas the mouse isn't even in the playable area, it's on the canvas. How do I convert the mouse position from its real position to what it would be in the playable area?
@frosty sequoia depends on your camera type is is ortho or perspective?
Ortho, sry for not clarifying lol
mouse position is in screen space, this converts it to world
for perspective its a little move involved, since you need to do a ScreenPointToRay and cast into the scene
but for ortho that should be enough, will give you a point on near plane of the camera based on a screen point
Yeah I'm using that but doesn't that just give me the mouse location that's on the canvas? I want to convert that position to where that would be in the playable space
are you calling it from the camera that renders the world and not the UI
How can I call it from the UI?
well if you want it for the playable space would you not want to do it from the games main camera?
or are you needing the ouput to be in canvas space?
It needs to be in the canvas space
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.RectTransform.rect, Input.mousePosition, uiCam, out var localPoint)```
Im running into an issue... I have a QuestManager, with questTasks inside with [SerializeReference] attribute. If I change scene during a specific task, the reference in the next task is set to null, even although everything seems correct in the inspector, the object is still there
It doesn't look like a bug in the QuestManager itself, but something within unity
BTW I am using Odin Inspector
Nvm I wasted your time sry, it's apparently a complete different problem that caused these issues
Quick question, if a Coroutine begins on an object, then the object is destroyed, does the coroutine still execute?
nope
π cheers
the coroutine executes on what ever called StartCoroutine
so it is possible to run the function from 1 thing on a other objects StartCoroutine if needed
disabled objects also do not tick coroutines along
Currently trying to use "if object still exists, do this after x seconds", so this should work out
So this does convert the screen position to the world position like in the playable area where the camera is pointed at and not where the canvas is, which I didn't know. So that should all be fine but I'm trying to figure out why my mouse doesn't line up with where it should? Like what my mouse says is 0 y is actually like 16.75 y? Does anyone have any ideas as to why this is
its hard to say without knowing more about the scene setup
but it takes a screenspace coord and gives you a worldspace coord that would be on the near plane of the camera
its mostly only useful for a ortho camera
I am using an ortho camera. I can't really send any screenshots cuz my internet's out so I'll just send a photo
yeah should be fine, if anything is wrong i would expect the z to be wrong
since it will be close to the cameras z coord
The plot thickens. Found out that the bottom left corner is accurate. Which makes a lot of sense now that I think of it actually
Hey all, how do I reduce the speed an object rotates based on its difference in rotation to another? I'm trying to slowly reduce how much AddTorque I apply to slowly rotate to match a "ghost"
that way when I stop input, the physical version still seeks the ghost position
Same "physics object follows ghost" physics concept as VR, but in 2D
Nevermind, it was my code lol
Welp I've constructed some sort of monstrosity so here goes
clawLeft.AddTorque(clawArmSpeed * (360 / (clawLeft.transform.rotation * Quaternion.Inverse(clawLeftGhost.transform.rotation)).eulerAngles.z));
this isn't helping at all so if anybody has any suggestions π
how about inverselerp to get a 0-1 value based on how close the current rotation matches the target rotation
then you multiply your torque force by that
i'd be interested to see what you come up with if it works ^^
not sure if there's an InverseSlerp
since you're using rotations
dot product of the forward vectors would give a similar 0-1 value as well
well in that case -1 to 1
that actually might work better so I don't have to worry about when to inverse, it would just know
Wait that sounds wrong
idk I'll try that if I struggle with this
uhh
Wouldn't I need to be able to calculate how far it is from its hinge angle limit, and that would need to figure out the direction it's coming from frame?
hehe guess I'll be tinkering for another hour
thanks for the suggestions, gonna need to read for a while probably
oh yeah inverslerp is going great, just gonna take a lotta optimizing now, thank you again!
can I see how your inverselerp is being used?
i havent used it personally
I'm still having some issues getting it to work perfectly actually, but this is my WIP Mathf.InverseLerp(-20.5f, clawLeftGhost.transform.rotation.z, clawLeft.transform.rotation.eulerAngles.z)
but it's directional, so that's only for the left to right rotation
when scrubbing floats in the inspector, is there a way to increase the resolution of it? holding alt for 0.01 isn't fine enough for this case
Sorry, just saw this
I meant the "line" that designates perpendiculars of both
That way I can just average them to make the "corner normal"
Unity's script reference is making me think I have to go through all the paths in a polygon collider and find the pair of points I need to do the math to get that myself
while (transform.position.y < 4)
{
rb.velocity = new Vector2(0, speed * Time.deltaTime);
}
Why does this freeze Unity and how could I fix it?
probably because transform.position.y is never less than 4
make sure you set speed to something other than 0
and that it'll lead your transform.position.y to less than 4 eventually
It's a while loop. The position doesn't change until after the loop exits
Make it an if (transform.position < 4), and it shouldn't crash
Or you need to check the speed and have that be part of the while loop's break requirement
but doesn't rb.velocity already alter the gameObject's position to above y4?
No
That means it has that velocity
That doesn't mean the object is physically moving
That means it will move next time the rigidbody updates it's position
However, since the position never changes during the while loop, you created an infinite loop
np
My progress but issue, 1 - Mathf.InverseLerp(20.5f, clawLeftGhost.transform.rotation.eulerAngles.z, clawLeft.transform.rotation.eulerAngles.z) is working correctly and returns a value that shrinks as it approaches the rotation
Mathf.InverseLerp(-20.5f, clawLeftGhost.transform.rotation.eulerAngles.z, clawLeft.transform.rotation.eulerAngles.z)} the exact same equivalent, but with a negative number, always returns 1
does it not take negatives ;-;
It should work with negative values as well. Debug the involved values to see what's happening.
Hey friends, back at it again with a question. I have a ScriptableObject with some values and I want a bunch of my gameobjects to grab those values. Right now they grab them on update but I want them to be more observer based and only grab them if they change. I'm pretty inexperienced with getters and setters but is there a good way to handle this with a scriptableobject? initially i wanted to use a unityevent or something like that but of course i can't do that in a scriptableobject
Why can you not do that in a ScriptableObject?
I have implemented some example code for creating a pretty solid PropertyChanged Pub/Sub system, its not on a scriptable object so you'd have to copy paste the code and modify PropertyWatcherBase to inherit from it, but, aside from that the rest should work fine
https://gist.github.com/SteffenBlake/ace74a893d0b16c30a7eb2a42d6d9230
So the one tweak you would make, I believe is just:
public abstract class PropertyWatcherBase<TSelf> : ScriptableObject
where TSelf : PropertyWatcherBase<TSelf>
{
I have the gist setup to largely just be copy paste / drag and drop in, it should largely work as is, and you can see the example code snippets in the comment I posted on that gist on how you use it, it's pretty easy to use and IL2CPP compatible
I can create the event but how would I invoke it?
Via code..?π€
Ooo I will read up on this and see if I can wrap my head around it π
I can't run code in a SO, no?
I think they're asking for the details
the examples at the bottom show you how to use it, it's pretty straightforward overall
Of course you can.
π€
Doesn't seem so.
I would also recommend @night harness, personally, you drop the scriptable object part entirely and just use injected POCOs via dependency injection, cuz scriptoble object singletons add a lot of extra work that really doesnt serve much purpose
thanks!
Well, yeah, PixxelKick helped them how they needed it. That's what I meant.
once you break free of the limitation of needing to make all your random scripts and code have transforms in the world and instead have actual ephemeral services that just... run and do stuff, without having to exist "in" the scene, life gets a lot easier
You threw a lot of perms at me that I might not be ready for at this present moment. On a higher level I do understand where your coming from though, I am a little chained down by my short visioned unity pilled-ness
POCOs just mean plain ole classes, not scriptables, not monobehaviors, just class
at the very least it's just a ref. i grab from my gamemanger singleton that I need anyway so it's not too bad but yeah im slowly wrapping my head around detatching myself from actual gameobjects
I actually had that revelation yesterday with the detection stuff I was doing
Id say a solid 95% of my code is just on POCOs that just run in the background as a service, no need for all the weird unity stuff, they just run and they "just work"