#archived-code-general
1 messages · Page 276 of 1
AFAIK editorconfig should be respected automatically, if it's not working you can double check if you have set your formatter to the C# Dev Kit one.
yes, it has worked more or less flawlessly before.
Hey everyone, I have this code that automatically adds prefabs to a list. I was wondering if it's possible to have it trigger every time a new asset/prefab has been created?
private void FindPrefabs()
{
prefabs.Clear();
prefabBank.Clear();
string[] lGuids = AssetDatabase.FindAssets("t:GameObject", new string[] { "Assets" });
for (int i = 0; i < lGuids.Length; i++)
{
string lAssetPath = AssetDatabase.GUIDToAssetPath(lGuids[i]);
if(AssetDatabase.LoadAssetAtPath<GameObject>(lAssetPath).GetComponent<Saveable>())
{
prefabs.Add(AssetDatabase.LoadAssetAtPath<GameObject>(lAssetPath));
}
}
for (int i = 0; i < prefabs.Count; i++)
{
AddObjectToPrefabBank(prefabs[i]);
}
}
it certainly is. you need an AssetModificationProcessor class which implements the OnWillCreateAsset method
Hey all. So I have a script that uses spherecast to detect enemies, to then inflict damage. Each of my enemy objects has multiple body parts with tag Enemy. I want to limit the spherecast to register only once per enemy. At the moment it just registers too many hits and lags a lot.
For example, the moment a body part of enemy 1 is registered, the rest of the spherecast cannot register hits for any of the children colliders of enemy1.
Any ideas?
Pretty sure that SphereCast return 1 hit ?
im using foreach (RaycastHit hit in hits)
Are you using: https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html instead ?
group them by Rigidbody or Enemy script.
But yeah, usually you should have a rigidbody to prevent such situation.
HashSet<EnemyScript> hitEnemies = new();
// then in the loop:
EnemyScript enemy = hit.collider.GetComponentInParent<EnemyScript>();
if (enemy != null) hitEnemies.Add(enemy);```
then your set contains the enemies that were hit, no matter how many colliders you hit
Okay thanks a lot I will try that and report back!
hey, im trying to make a leaning mechanic in an fps controller, and it only seems to work when the rotation target is positive (leaning left)
when i try and lean right, it spins the whole camera around 360 degrees and keeps doing that until i let go of the button.
private void CalculateLean()
{
//if(inputLean == 0 ) return;
Vector3 tgt = Vector3.zero;
tgt.z = -inputLean * leanAngle;
Debug.Log(tgt);
if (Vector3Int.RoundToInt(leanHolder.localEulerAngles) != tgt)
{
leanHolder.localEulerAngles += Move(leanHolder.localEulerAngles, tgt, leanSpeed);
}
}
private Vector3 Move(Vector3 start, Vector3 tgt, float secs)
{
Vector3 diff = tgt - start;
Vector3 move = diff * (secs / 50);
return move;
```
euler angles->Quaternion != Quaternion -> euler angles
what do you mean?
I mean than if you put a Vector3 into an euler angles and then turn the euler angles back into a Vector3 the chances of them being the same are virtually zero
no you misunderstand.
you do leanHolder.localEulerAngles += which will be converted into a Quaternion
so when you read leanHolder.localEulerAngles that is being converted from the Quaternion and so the value that went in will not be the value that comes out
using euler angles is a mistake
ive tried using quaternions to do this but im not sure how to do the maths in Move() with them
Also not sure what this Move function is but it seems like Quaternion.RotateTowards is more what you want?
{
Quaternion tgt = Quaternion.identity;
switch (inputLean)
{
case 0:
break;
case 1:
tgt = Quaternion.Euler(0,0,-leanAngle);
break;
case -1:
tgt = Quaternion.Euler(0,0,leanAngle);
break;
}
Debug.Log(tgt);
if(leanHolder.localRotation != tgt)
{
Quaternion.RotateTowards(leanHolder.localRotation, tgt, Time.deltaTime);
}```
this is what ive got now, the tgt is being updated properly but it just isnt rotating at all
wait
i think i used the method wrong 1 sec
you're not using the result of RotateTowards
also Time.deltaTime should be multiplied by a speed
yep, done that too
otherwise it will be 1 degree per second
thanks for the help!
(nvm me, chat didn’t update)
Heya all, I'm doing a bit of procedural world generation and I'm having some problems with textures on sharp edges. This is because there is literally no vertices between the top of the cliff here and the bottom. This is done as it's based on x and z world coordinates. I know how to fix the uv, that's not a problem, but If I wanted to add some detail onto it using more vertices, how would you recommend doing so? https://gyazo.com/d57b21696448347019528691a7407a0a
Also ignore how shitty it looks for now
I'd recommend looking into triplanar shaders
I have an issue with a ArgumentException: method arguments are incompatible error that i can't understand the reason of and can't seem to make it go away no matter what i try. Here is my code. The error is on the line object value = property.GetValue((object)node);
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
maybe object value = property.GetValue(node);
makes no difference
hmm yeah nvm then.
I'd start debugging what is being passed in instead and why they are incompatible
why object btw
because GetValue returns the value as an object
Debug.Log the PropertyInfo that this is failing for and the type and the node object
also hastebin might keep the indentation of your code for us to read it better. instead of the .txt
i figured out the issue. The class whose properties i was trying to access was derived from a class wich had an indexer. I fixed it by only getting the properties declared directly in the class i needed.
`var derivedType = node.GetType();
foreach (var property in derivedType.GetProperties())
{
if (property.DeclaringType == derivedType && property.CanRead)
{
object value = property.GetValue(node);
if (value != null)
{
nodeData.properties.Add(property.Name, value);
}
}
}`
Makes sense. The indexer would be a property that has a parameter, which would cause that error if no param was provided.
iirc you could kind of always do that, it just works inconsistently depending on what you changed/where
Ahh ok , never noticed, ig a simple Debug.Log isnt exactly a breaking change lol
added reference to a transform and able to move via translate and still didnt break while in playmode, kewl
I have the hot reload asset and it's pretty good, but even that still feels kind of sad in comparison with JS frontend world, where you get hot reload in two digit milliseconds and there rarely ever are things that can't be patched and requiring a full reload.
That's always the tradeoff of compiled vs interpreted languages
Hmm it certainly contributes, but I wouldn't say that's why hot reload is bad. Even in regular C# hot reload is pretty decent, nowhere near Unity's tens of seconds or even minutes to do a rebuild.
other JS libraries you still need to restart, esp if you work with node
That's no longer frontend if you are talking about Node.js, but even with Node.js the restart time is still sub two digit milliseconds.
oh vanilla js ig sure, but thats boring 😛
The past few days I've been writing WebSocket stuffs and I have a Node.js WebSocket server running on watch mode, it auto restarts faster than I can even Alt + Tab away.
I just do everything in c# now, hate working with js tbh
I am trying to remove a line from a TMP Text how could i do that? for example if i have 9 lines how do i delete the 9th line?
a string operation probably
are they split already with \n ?
Yes
so you have an array of lines?
I write mostly C# and TS, they combine cover basically everything I need. C# is generally pretty bad with UI stuffs, and TS covers that nicely.
which bad UI ?
Have you tried Razor ?
combines HTML with just writing C#, you can also add JS functions/frameworks ofc
Just what I was looking for! Thanks very much
yes i do
string existingText = streamChat.text;
string[] lines = existingText.Split("\n");
StringBuilder sb = new();
int maxLines = 8;
for (int i = 0; i < maxLines && i < lines.Length; i++) {
sb.Append(lines[i]);
}
string result = sb.ToString();
streamChat.text = result;```
ahh wrote it faster
Are you building some sort of rolling chat where only the latest 8 messages are shown?
Do you get each message individually?
its just pulling a random string from a list depending on what is going on in game
Much better with string builder, I was doing Split n Join 😛
Honestly way better to just keep a Queue<string> around containing the lines rather than do this string manipulation and splitting
If that's the case, rather than "adding the latest message to the full text, if it goes past 8 lines, split the text and remove the excess" which is a lot of unncessary work, you could instead use a Queue<string>
Im pretty new, how would i implement a queue into this?
Enqueue one every time you get a new message, and dequeue one whenever it goes past the 8 limit.
lookup the docs, its easy
Dequeueing will manually remove the line?
Queue<string> messages = new();
void Display() {
StringBuilder sb = new();
foreach (string message in messages) sb.Append(message);
myText.text = sb.ToString();
}
void AddMessage(string message) {
messages.Enqueue(message);
while (messages.Count > maxMessages) messages.Dequeue();
}```
this is pretty much what you need
Okay ill try to implement this
thank you sm
should i be running display in update?
this datatype is First In and First out
If you don't care about optimizing that tiny bit of allocation (presumably your chat isn't going to be like Twitch chat rolling all the time), Display can simply just be string.Join("\n", messages); and that's it.
no, pretty much whenever you add a message
you could even call Display() at the end of AddMessage
It will be running pretty much the whole time, so this will work better because i need optimization
You probably don't need it, but oh well it doesn't hurt.
AddMessage is how you add a line of text
delete the first two lines in SendStreamMessage
Thats what enqueue is doing huh
that's what AddMessage and Display are doing
AddMessage is adding the message to the queue
Display renders everything to the Text object
in VS, is there a way to cycle the suggestions of c# autocompletion? it wants to complete this bool to true, when i want false. i would like to do something like press the down arrow to go to false. i am not finding a way to do that and google and CGPT has been useless for some reason
if you mean you are seeing something like = true; in grey to tab to complete, that's intellicode and you'd probably want to look up the settings for that
I remember someone here talking about his asset, a sort of better version of NaughtyAttributes.
does anyone has an idea of what I am talking about ?
I added a ui blur, and it dropped my fps from 200 to 100
Yeah sorry, i was not clear. I am looking for an intellisense hotkey to flip = true to = false in the intellisense suggestiong
that is not intellisense. that is intellicode
same question, but with intellicode instead of intellisense then 🙂
and you can look at the settings to see if that exists. now that you know what settings you would need to look at
ok, so you are not aware of one preconfigured. guess i need to hunt more
Whenever I use Debug.Log in my code, Visual Studio 2022 feels the impeccable need of adding System.Diagnostics to my libraries, which then causes an error. How can I stop it from adding System.Diagnostics?
well do you want the auto-import namespaces feature
Intellisense settings matches the concept better than intellicode settings. mayber there are hidden intellicode settings? it is like they are symbiotic. completion list advancement, and showing a list with true and false, is basically what i am after
intellicode is just an AI code prediction thing. it's not really meant for what you are trying to do
how can I call an animation event with my script ?
is this box intellisense or intellicode?
that is intellisense
you just answered my question
thx
Ok, i am hoping for that box, but with true/false option when typing a bool. then like, pressing a down arrow to switch between the two. This is all i am getting right now though: Image. No box with options, just the one incorrect suggestion
that is intellicode
well, i am changing their names to stupicode and falsesense :/
seems like there should be a hotkey to toggle true/false there
intellicode is just AI trying to predict what you were going to type. it's not going to be a replacement for you typing your code
Intellisense is not really intended to write your code for you. Imagine that was an int. Should there be a toggle for evey possible number? Just type t and it will fill in true for you
yes 🙂
- Is there any way to create asset menu for a specific scriptable object type without putting an attribute on it manually but programatically? My last bet is reflecting the attribute to the type, but perhaps there is some api i'm missing or something
but seriously, what i am looking for is a combination of the two. When i enter a bool, the selection box should come up so i can down arrow to false or true. it is just an extension of what it is already doing. it is not writing code for me, it is assisting with data entry
usually i use VoiceAttack and just talk to type code. I have not taken the time to configure it for Unity C# yet though. in the end, it is just utter laziness on my part 🙂 (the desire for the bool toggle i mean)
when you guys use git, do you do commits etc via VS, GitBash, or something else?
idk if the VS git features will only include the actual solution, or if it will include all the other files
I just use github desktop, gui is the way.
Most all version control has a desktop gui.
i see. I would like to set something up to avoid github, to keep everything local. is there a good gui-based program you would recommend?
You just install GIT and push locally but if something happens to your harddrive you will lose it if you dont back it up. Thats the point behind local vs remote changes
i would like to set that up later, to have a backup drive or something
Most all IDE's will detect that you have GIT installed somewhere around your terminal window within the IDE
so multiple computers can connect via local network
Would be a lot easier if you just use github and a private repo. I dont remember if github desktop can work locally like that
i assume github would be easier tbh
I wonder if i had something like VisualAssist, or Rider if it would do that by design. not really important right now as i will not be investing in either anytime soon
maybe I’m just paranoid, but i’m just not sure how much I want to be transmitting information over internet. especially since my github account is more easily seen, and then compromised
What's to stop a dedicated attacker from breaking into your house and stealing all your hardware?
No need to be so concerned about it. A private repo is fine
thanks for the info. would have taken me quite some time to determine what was what there
im trying to import a video file with transparency, issue is, im on linux.
for some reason unity on linux only supports the webm format, and only specific versions of it using specific codecs.
and no matter what method or programs i use, converting a video i rendered from blender with transparency into this format always gets rid of the transparency.
ive tried exporting from blender directly to the correct format but it doesnt support the right codecs.
ive simply got no idea how to do this
perhaps try in #🔀┃art-asset-workflow
I have an SO with a [SerializeField] private string myString field.
If I have the SO’s own method modify it in context menu, then the newly serialized value DOES get saved to file. If a different script calls that same method to modify it, then it does “change”, and looks different, but the file for the asset has not been changed!
Any idea why this might be?
Main relevant method in my SO looks like this:
/// <summary>Write whatever is in the class type references to the backup. </summary>
[ContextMenu("Backup Classtype references")]
public void BackupClassRefSave() {
TryBackup(conductStrat, ref backupConductStratName);
void TryBackup(TypeReference typeRef, ref string backupName) {
backupName = typeRef.AssemblyQualifiedTypeName();
}
}```
this is what happens currently and i want the plane to fall more when the angle gets too high and ive tried for about 10 mins now cant figure out does anybody know what i could do. Also this is my code: https://paste.ofcode.org/L2yGNu2M3QGNxS9HQMYmnv
It is extremely simple and the whole thing heavely relys on the unity physics system.
i want the plane to fall more when the angle gets too high
This is extremely vague
btw you are making some classic mistakes here in your code.
Physics belongs in FixedUpdate, not Update
and you shouldn't multiply the forces and torques by deltaTime once you move it there.
Think I got it working, thanks for the help (forgot to reply earlier)
Is there a best-practice pattern you would recommend for pausing logic triggered by invoke?
I have an event based pause setup rather than using time.timeScale=0 but im not sure what a good way would be to get invokes to hook into that system. In some cases, I've just replaced the invokes with a timer controlled by the component that can be pause/unpaused when it gets an event but I'm wondering if theres a better way I can set up delayed logic such that it could integrate into that system, like a way to pause all invoke timers on an object
coroutine
Can coroutines be paused? I see StopCoroutine functions but I assumed they would cancel them completely
coroutines have WaitUntil
Hello, does someone knows if it is possible to have .csproj not in the unity project directory as if it was a third party library ?
I want to have a project outside of unity project directory because i'm using it for a .Net console app and some code will be used inside the unity project but i don't want to build a dll from it and move it to asset folder.
and any time based WaitFor… do not advance if timescale is 0 iirc
so if I have
yield return new WaitForSeconds(delay);
I'd just have to make calling that conditional against my pause bool?
does your pause set timescale to 0?
it should
because if timescale is zero, WaitFor… any amount of time will not be ready for next call to advance
nah because i want the ability to only pause certain things
theres like layers of pause
you could do WaitUntil(!pauseBool)
but know that if not paused, that will probably make it yield to the next frame still
right ok. thanks for the info.
but that is the general premise anyway
hey so I'm trying to simulate circular motion without using trig functions - I have a sphere with a RigidBody initially at (-5, 0, 0) and I add an initial velocity of (0, 0, 5). I add mv^2/r force every update method but it seems to just accelerate the objec tto infinity. any reason this is happening?
using System;
using UnityEngine;
public class CircularMotion : MonoBehaviour
{
Vector3 center = new Vector3(0, 0, 0);
public Rigidbody rb;
int rad = 5;
// Start is called before the first frame update
void Start()
{
rb.velocity = new Vector3(0, 0, 5);
}
// Update is called once per frame
void Update() {
Vector3 direction = center - rb.position;
float v2 = (float) Math.Pow(rb.velocity.sqrMagnitude, 2);
rb.AddForce(v2 / direction.sqrMagnitude * direction.normalized);
// Debug.Log(rb.mass);
}
}
for starters, you really shouldn't be adding force inside of Update, higher framerates will end up adding more force than lower framerates as a result. physics should be performed inside of FixedUpdate
and for preventing it from just constantly speeding up you'd need to set up drag on the rigidbody and also possibly clamp the magnitude of the velocity
oh i see
why would drag/clamping be needed though? is it because the addforce isn't exactly precise leading to speeding up? because theoretically the force shouldn't change the velocity of the object
Do some math on paper.
As it is now it would always move towards the center. You need some kind of counter force.
Force always changes the velocity of the object.
Otherwise there wouldn't be a point in it.
huh iirc at least physics wise if the force is perpendicular to the velocity of the object it wouodn't do any work on the object, and so the kinetic energy/velocity stay the same
Not sure where you heard that, but it doesn't matter what direction the force is applied at relative to the velocity, it would always affect it.
If it applies perpendicularly, it would just add sideways velocity.
hmm so how does centripetal force work in unity then
or how would i simulate that?
Actually. Wait a moment. I think my physics memory is getting rusty.🤔
have you tried your current code inside of FixedUpdate to see how it behaves on the correct time step? because as it was before, you were adding extra force on non-FixedUpdate frames because update typically runs many more times per second than FixedUpdate does and FixedUpdate runs on the same time step as physics being updated
yeah fixedupdate still seems to accelerate it to infinity, i'll try clamping the velocity
how would i do that?
just rb.velocity = rb.velocity.normalize() * constant?
You're right, this should work under the conditions that no other force is applied(like gravity)
Can you record a video demonstrating the issue?
Because it's not clear wether it just keeps on going in one direction or accelerating while orbiting.
sure
Also, just a correction about what we were talking before: applying a centripetal force to the object would make it's velocity change. It should keep the speed(velocity magnitude) constant. But when we talk about velocity, we imply it's a combination of direction + magnitude.
its kinda hard to see since it happens so fast..
okay got it
As for the cause, it's probably because you got the formula in unity incorrectly.
The way you have it now is F = v^4/r^2.
oh
sqrMagnitude is squared magnitude after all.
Instead of squared magnitude use the regular magnitude
If I have a shape defined by a set of vertices (Vector2 points) in an array (point 1 connects to point 2 and so on, with the last point in the array connecting back to 1) how would I check if an object is within the boundary of that shape?
Hey sorry to ping after a while lol. I've managed to get the screenshot working and saving it to a folder. But I can only get it to screenshot the entire screen. I don't really understand how the parameters for ReadPixels() relate to the region it captures.
How can I use my animation events in a script
I have this script https://hastebin.com/share/ucefipecew.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What do you want to do with them? Generally, you set them up in the animation, they call a function, and you have to have that function in your script and it'll get called
yep but i can't add the function
why not? you just type public void MyFunc(params if you have any) { code goes here }
yes but it's not gonna happen at the same moment than the event
it's just a function
a function that the animator/animation component will call when it reaches the event
this is where it doesn't work
okay... show how you've set up one of the events
i can't add the function
you must have the function first, I guess
(I don't quite remember how it works)
you must have a component with the function, which should be attached to the object that you're animating... something like that
glad it worked, happy to help 🙂
hi. I ran into a funny situation. I am using
Int.Parse("+1")
in some code, which ran fine on my system. apparently this is because the default for NumberStyles is to allowe leading sign?
However, on someone else playing my game, this resulted in a exception and their game crashed lol
how would their system interpret this differently, we even checked their .NET version
and it was very similar, mine was 7.0.306 and theirs was 7.0.202
I guess to be safe, I should just use
Int32.Parse(num, NumberStyles.AllowLeadingSign) to be explicit?
that's an option, buuut normally you'd pass CultureInfo.InvariantCulture
ah, yes I come from a very typed background
I see that as a solution too
but, I prefer to be very strict about typing if possible
maybe passing NumberStyles is better, I haven't checked exactly how it works... just make sure it describes it well enough and doesn't depend on any user config
actually, is the string that you're parsing coming from user input?
I'm not even sure I totally get the InvariantCulture thing tbh... this is the first I've heard of it since you just mentioned it lol.
nah it's just from some prefab stuff i have
i can parse it however I want
its not really a big deal, i'm just super surprised that it would run fine on many systems, and then all of a sudden crash on someone else's
InvariantCulture is just constant in how it handles things and doesn't depend on user settings
ah cool! maybe that's what I need indeed
mm, parsing numbers is tricky... in some countries they use . as float point delimiter, and in others they use ,, and so on
there are spaces, no spaces, commas for thousand separators, etc.
fun stuff lol
and that's based on device settings, lets say
InvariantCulture is not based on settings - it formats and parses things in the same way for everyone 😄
makes sense! I wonder if somehow Integer parsing is culture dependent, based on a user's system
that would explain the issue
it is, yeah, that's why you can pass all these settings in 😛
oh interesting, so would that have to do with the native language they use on their system? or would it be based on where the OS was purchased from?
language settings
(language and region on Windows... you can specify custom formats and stuff in the settings, I believe)
you're a hero, thank you thank you! ok i should probably go to sleep getting my schedule all messed up is not fun xD
have a good one!
thanks, you too
Dudes, one question about architecture selection for data in a game. I love component based approach but it needs clear design for data beforehand.
It means it is so easy to have a separate definition class for each element/item type in the game.
For example in a simulation game with a bunch of different items, it is hard to pack their properties to different components unless the design is clear. What do you think?
Clear design beforehand is not a thing, imo 😄
And the nice thing about component based approach is that you can make it piece by piece - one component only needs to know about X data and manages it itself. What other components may or may not exist - you don't care.
Of course, over time you'll see better ways to organize things, and every now and then you'll refactor. 🤷♂️ 🙂
thanks @little meadow
Yes, if I use component based approach for data, I can easily inject them into the correct component (mono/behaviour/logic), Also, it reduces the number of similar scripts
I am afraid of reaching the point that it is hard to group data to modular components or at least some props are in components and some of them are not,
The problem is that I have separated data/definition (SO) from logic (components in prefabs)
The desire is to map the correct data to the correct component (mono)
public class Repairable : MonoBehaviour, IRepairable
{
public event Action Repairing;
public event Action Repaired;
public int MaxUseCount { get; private set; }
public int Count { get; private set; }
public bool IsOutOfOrder { get; private set; }
private void Init(ItemDefinition definition)
{
var repairableDefinition = definition.GetComponent<RepairableDefinition>(); // here, component based approach
MaxUseCount = repairableDefinition.MaxUseCount;
IsOutOfOrder = false;
Count = 0;
}
Hey, why doesn't it work?
I use unity 2022 LTS
public class Def:SerializedScriptableObject{
public IDefinition Component;
}
public interface IDefinition
{
}
[Serializable]
public class RepairableDefinition : IDefinition
{
public int MaxUseCount;
}
I get an error below
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUILayoutEntry.ApplyStyleSettings (UnityEngine.GUIStyle style) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutEntry.set_style (UnityEngine.GUIStyle value) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutEntry..ctor (System.Single _minWidth, System.Single _maxWidth, System.Single _minHeight, System.Single _maxHeight, UnityEngine.GUIStyle _style, UnityEngine.GUILayoutOption[] options) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutUtility.DoGetRect (System.Single minWidth, System.Single maxWidth, System.Single minHeight, System.Single maxHeight, UnityEngine.GUIStyle style, UnityEditor.HostView.OldOnGUI () (at <5d5ebefe97114215928ac1d9cd096522>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <f67debe1efd242948106f1922bfac1c7>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
i need some help with MediaPipeUnityPlugin anybody ever worked with it here? need to convert landmark positions to unity coordinate system or rect
Can somebody help me wrap my head around something?
- I store my attack parameters (like, damage, animation, etc) in scriptable objects. In theory every NPC should be able to use any attack in the game.
- I wanted to also store attack's effects logic in Scriptable Object (Like, how the attack is actually performed). But this didn't fly since the logic would require storing information about the target of the attack, but SO is shared between everybody who would use that attack so they will conflict overwriting the target-specific variables.
- So I decided to handle out NPCs an
AttackObjectclass object that the scriptable object can create withGetAttack()function, instead of the reference to the SO itself. This class would contain the logic for the attacks and data relevant to the attack.
Now I came to the problem of associating those attack classes to the scripted objects of the attack parameters, which attack should issue out which AttackObject subclass. Ideally I want the SO to have a variable exposed to the inspector, a dropdown list of the AttackObject class inheritors I can chose from, but how do I make something like this?
Naively making a serializable field didn't work, of course...
[SerializeField] public Type attackLogic;
I'm actually working on releasing a package that does this +1-2 other things 😄
You need [SerializeReference] + a custom property drawer
I'll probably make the repo public sometime today, and can link you if you're interested in being the first user 😅 (though in the interest of fairness, other repos with such a feature do already exist)
Interesting, so it would be [SerializeReference][SerializeField] public AttackObject attackLogic;? It does show in the inspector... But how do I collect inherited types for the dropdown in the custom drawer?
It would be more like [SerializeReference] [TypePicker] private BaseType fieldName; and the drawer of the TypePicker is gonna draw a type picker... you can get the classes using... TypeCache.GetTypesDerivedFrom(type) it's a Unity thing
Oh, thanks! I'll dig into that
Can coroutines run in parallel? Like using multiple cores? Or do I need to use the job system for that?
Coroutines run on the same thread as everything else. You can use .NET's task system or UniTask to do stuff on other threads, but keep in mind that everything that related to any Unity component requires running on the main thread.
thanks, I just need to load beatmaps and mainly songs into memory, so that should be fine
The job system, of course, is also an option... I'd say job system is more for doing heavy computations in parallel, whereas the task system is more about doing async stuff (like writing files, downloading stuff, which may take a while)
oh, okay. thanks :)
My bullets are fixed in the air even if my script tell them to move, do someone know why ?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is there a shortcut to create a vector 3 with same x y z ? like Vector3.one
using a float var
Vector3.one * x
value * Vector3.one
To expand on this, UniTask also allows you to run tasks on the main thread, so it can replace coroutine completely, with better performance and all the async/await goodies like return value, cancellation, etc. I highly suggest it if you do a lot of asynchronous programming than to endure how bad coroutines are.
problem solved ! The speed of the bullet was null.
I think I got the basic of it, but it seems I don't know how to assign the new variable. It gives me null exceptions...
[CustomPropertyDrawer(typeof(TypePicker))]
public class TypePickerPropertyDrawer: PropertyDrawer
{
private string _selectedType = "";
public void TypeSelected(object type)
{
_selectedType = (string) type;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
_selectedType = property.managedReferenceFieldTypename;
if(property.managedReferenceValue?.GetType().FullName != null)
_selectedType = property.managedReferenceValue.GetType().FullName;
string clearName = _selectedType?.Split(".")[1];
EditorGUI.BeginProperty(position, label, property);
if (EditorGUI.DropdownButton
(
new Rect(position.x+property.depth, position.y, position.width-property.depth, position.height),
new GUIContent(_selectedType),
FocusType.Passive
))
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent(clearName), _selectedType==property.managedReferenceFieldTypename,TypeSelected,property.managedReferenceFieldTypename);
TypeCache.TypeCollection types = TypeCache.GetTypesDerivedFrom(fieldInfo.FieldType);
if(types.Count > 0)
foreach (Type t in types)
{
menu.AddItem(new GUIContent(t.Name), _selectedType==t.FullName,TypeSelected,t.FullName);
}
menu.ShowAsContext();
}
// property.managedReferenceValue = (UnityEngine.Object)Activator.CreateInstance(Type.GetType(_selectedType), new object[]{});
EditorGUI.EndProperty();
}
}
where does it give you a null ref?
In the commented out line
so, see what's null on it and fix 😛
but why do you have a cast to UnityEngine.Object?
I couldn't figure out how to cast to the specific type I selected, everything I tried gives me syntax errors. T_T
[SerializeReference] doesn't work with UnityEngine.Object... if you want those you just use a normal field with [SerializeField]
you shouldn't need a cast on that line
Hm, I can swear it was giving me "cannot convert..." error before without the cast, but now everything's fine... >_<
Anyho, I think I've located the error down to Type.GetType(_selectedType) not returning anything. X_x
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
is cableMaskLayer an actual layer in the Unity Inspector?
you can see it on the screenshots
I have an issue in an SO:
[SerializeField] private string backupConductStratName;
/// <summary>Write whatever is in the class type references to the backup. </summary>
[ContextMenu("Backup Classtype references")]
public void BackupClassRefSave() {
TryBackup(conductStrat, ref backupConductStratName);
void TryBackup(TypeReference typeRef, ref string backupName) {
backupName = typeRef.AssemblyQualifiedTypeName();
}
}```
If I use the context menu to call this method in the inspector for the SO, the value of backupConductStratName DOES get updated and written to file.
If I call this method from a different SO’s method (also context menu in editor), it looks and behaves like the string is modified. But it doesn’t save it to the file!
Any idea why?
So you're writting to an SO from another SO and the values aren't being serialized?
it is like the SO is changed, but the changes did not get written to file. so when I close and reopen the project, it’s loke nothing was changed
yes. I have a directory SO with context menu method, that goes through all of THIS SO in its list, and calls the Backup method I wrote above
Yeah, I think I've ran into this issue before, and it was when I've decided to try to write to my SOs instance when running the game.
I think I hypothesized that it created another instance that I was writing to, and it would only revert when restarting the editor.
is there a way to just tell Unity to update and serialize the current contents?
when i view the editted SO in inspector, it looks modified. but the .asset file isn’t actually different
right, because it probably made another instance (or perhaps it's just not serializing the values)
probably some fail safe to prevent you from blowing up your asset by mistake
looks promising
could be something like a IsDirty flag you'd have to flip
but nothing I've really looked into since I realized pretty quickly that I shouldn't have been writing to them like that in the first place
i just don’t see any methods/properties/fields in SO that I can access whichbare relevant
this is an editor script, so theoretically not a problem
ah, yeah I was talking about my methods of writing to them
well, i can only use ForceReserialize if i can get the path for an SO
so… how do I get the asset path for an SO given a ref to the instance lol
assetpath
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);
// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);```
oh scratch the ID
ok, that is what I was about to ask.
only works editor but seems like that's what you're doing anyway
yeah, that is perfect
ty
i might make an extension method for SOs for this
damn. still trying to set up other IDE settings on windows, since I had to change computers
anyone know the name of the setting that makes VS automatically add using directives as you type?
wait wait
i disabled one for “add missing using directives on paste”, but that doesn’t count for my normal typing
there's EditorUtility.SetDirty
because with autocomplete, VS adds the stupidest shit
"Show types from unimported namespaces"
oh. i’ll see
It's the standard way to tell some Unity object that you changed it, so Unity would know to serialize it when you save next time, something like that
i see. this blocks the automatic using addition, but now if I write Action, it won’t tell me that it exists in System namespace
That setting enables it globally, but it can still be toggled from the completion list, using the green "+" icon bottom left.
oh i see the buttons to operate the menus are just different
not sure I follow.
potential fixes highlights nnamespaces, but I don't think that is what I was seeing on my mac
because potential fixes is it trying to fix the whole problem for me
Not on the tooltip, in the completion list
i’ll give that a shot. ty
With the feature enabled it will show the type name, and on the right in light gray the namespace it belongs in, if not imported
sry, i feel like i’ve been driving just fine, and now I’m in a weird european car where all the buttons are in different places lol
Ah, right I remember that method now.
I'm still a bit confused. This has show types from unimported namespaces on. This is the view I kind of want, but I don't want it to auto add namespaces.
because I end up with crazy namespaces in all my documents from random typos
It's not possible, as far as I know
ok. Off it goes then
Either you have them listed, and it adds the directive as you complete, or they're not listed at all.
I guess you'll have to stick to the Quick Actions to add the correct using directive, or Ctrl+Z to cancel if you chose the wrong one
And Ctrl+Space to bring the list back up
ty SPR
this is going to be a long and annoying process
anyway, since I finally have more tools, given windows VS is better, is ClassDesigner any good for coding?
i’m trying to see now that I have new toys what I have been missing out on
worked perfectly. thanks
happy to help 🙂 👍
i need to slowly get settled back in. ty for your patience
I have to set the player off and I am using the "SetActive(false)" function but the Player is still active
well, check what you're actually calling SetActive on
can I make a UI button do a different thing depending on right or left click? I feel like that was something I could do
The built-in Button class doesn't care about anything but left-clicking
Fortunately, it's very easy to extend existing components
it is?
Not through the OnClick callback. But you can certainly use raycasts or a combo OnPointerEnter/Exit
You can extend Button and override the OnPointerDown method
It receives a PointerEventData object
but I can just make it first click sets state to 1, second to 2, third to 0
instead of rclick and lclick switching stuff seperately
Actually, I bet you could just override that, along with OnPointerUp
and just rewrite the PointerEventData object so that it looks like a left click, even if it's a right click
and then just call the base method with the modified object
Otherwise, you'd just implement your own button logic for right clicks
Why?
If i follow an tutorial on 2d and the tutorial is 2d URP does it matter?
No
Please help, I can't seem to address the addressables to receive the list of keys; in the code snippet and image, everything seems to be configured correctly..
private async UniTask<List<string>> GetConfigKeys<TConfig>() =>
await assetProvider.GetAssetsListByLabel<TConfig>(AssetLabels.Configs);
private async UniTask<TConfig[]> GetConfigs<TConfig>() where TConfig : class
{
var keys = await GetConfigKeys<TConfig>();
return await assetProvider.LoadAll<TConfig>(keys);
}
Debug.Log(keys.Count) the result is 0
how do you profile the editor in 2022 LTS? the "profile editor" button is gone from the profiler
hrm... im trying to track down why it takes 3 minutes for me to enter play mode
ouch
I forget how much stuff appears in "Play Mode" and how much stuff appears in "Edit Mode" during startup
i haven't profiled that in a little while
my main menu was...uh, very Main, and very Menu
and was adding a half-second to my startup time
its happening in an empty scene, so it must be something in some asset i have in my project
how can I make my character move forward with new Unity Input System and Character Controlle
Make composite action binding and plug the vector into Move
oh ok, thanks
hello quick question do coroutines still run if the object having the script is destroyed ?
like if I destroy a gameobject while a coroutine is running on an associated script
if the destroyed object is what started the coroutine then the coroutine will stop
oh okay thanks thats what I was looking for
Is “Apply Scene Offsets” a deprecated feature or no?
I have to say, I prefer this channel... or the next one 😄
I mean, obviously there is going to be more beginners
So the beginners channel is, by default, more chaotic
I don't see much wrong in that
Oh, I don't see anything wrong in that as well 🙂 I just get more excited about some more challenging questions
does anybody know how I can check if the player isnt on a slope anymore after sliding down one
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Only thing I would suggest is using Mathf.Approximately(angle, 0f) instead of angle != 0 since a float is rarely ever going to be a perfect value - aside from that though, whats the issue with your current implementation? Your function should return false if the angle is greater than whatever you set maxSlopeAngle to be, if it is, you know your "not on a slope anymore"
Im not sure how to check during the slide
should I call the function on update and then check the angle?
if so, how?
You already are checking in (Fixed) Update, as long as you are not grappling, so your if-statement should remain true while you are on a slope, and false once you leave a slope (or in your logic, once your angle is greater than maxSlopeAngle)
so should I put an if statement in fixed update?
You already have one - you call MovePlayer, which checks OnSlope that handles your slope logic, maybe I dont understand how your current results mismatch what your expecting, cause your codes logic looks like you already do this
should I check if angle is 0 (or < 10 more likely) and if so turn the speed down
You could, if your goal is to slow the player down while moving on a slope
No my goal is to see if the player is no longer on a slope while stilling sliding and slow them down
if so
alr I changed the code a little and am using a coroutine to make the speed shift more smooth though tbh this isnt really related to the question
Anyone know how platformer/metroidvania games keep their camera from going "under ground"? In those games the camera only goes maybe a tile or 2 down like it's clamped or colliding with the terrain.
The effect works on walls and ceilings too I think.
didnt you answer your own questioon ?
it's clamped
But how does it handle so many different heights and variations
maybe it looks for specific object or tile?
Like each room and area is presumably at different heights and dimensions. You can't just set a floor and ceiling for every room
hard to say wihtout seeing their implementation lol
Yea I'm wondering if there's like a standard approach or guide on it
but if you have a "marker" type object too could also work
That's no bueno. Want a system that requires the least amount of setup I think
least amount of setup? what do you mean by that?
if the floor is passed as some sort of "marker" then they can check specific height comparisons etc.
Like no markers or tile level implementation. It should just work everywhere.
If there isn't a normal way I think I'll just try it with colliders and see where it goes
hows that extra work if it was say only the floor tiles etc.
Like 4 colliders for each direction and just check for wall collision before moving left and right
Ah I thought you meant setting specific markers. Yea wall/ground collision seems like an obvious first step I think
do you have a video example / gif ?
its been a while since i've played a 2D sidecroller
does anybody know how I can check the slope angle on update
Raycast
ik
I have a slope function
Im just not sure how to use the angle in update
Anyone here familiar with DryWetMidi? I want to pick your brains
I eat drywall, yes
You know DWM?
no
unimpressed kid gif
🤬
<@&502884371011731486>
source?
they can still see deleted messages
They see deleted messages
!ban save 833202238948114443 no tolerance for this
hylianmango was banned.
@swift falcon Move the hallway only
Not the player
Add sections far enough in front that you can't see it and far enough back for the same
oh shit didnt even notice lol
well I suppose dont have to answer the code question anymore
not sure what i did her but im trying to not have mouse POS value return to 0, more trying to have it return to its original possition after being used for the camera movement:
using UnityEngine;
using Cinemachine;
public class InputOnMouseDown : MonoBehaviour, AxisState.IInputAxisProvider
{
public string HorizontalInput = "Mouse X";
public string VerticalInput = "Mouse Y";
private Vector3 mousePositionOnMouseDown;
private bool isRightMouseButtonDown;
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
mousePositionOnMouseDown = Input.mousePosition;
isRightMouseButtonDown = true;
}
else if (Input.GetMouseButtonUp(1))
{
isRightMouseButtonDown = false;
}
if (isRightMouseButtonDown)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
public float GetAxisValue(int axis)
{
// No input unless right mouse is down
if (!isRightMouseButtonDown)
return 0;
switch (axis)
{
case 0: return Input.GetAxis("Mouse X");
case 1: return Input.GetAxis("Mouse Y");
default: return 0;
}
}
}
whatt are you trying to achieve here?
btw you made the strings but arent using them HorizontalInput
you can make those const
its a script for a camera movement thingie, being used along side cinemachine
doesn't explain its purpose or what your end goal is
it is supposed to move the camera relitive to the mouse movement once the right mouse button is pressed / held, the mouse meant to return to its original place when the right mouse button is clicked but instead it return to 0
where is supposed to return
I dont see any code to tell it to return
well no the Input.mousePosition is always moving
You wont be able to move the hardware mouse to that spot unless you're using the new input system anyway
unless you make a software cursor
I'm working with UI toolkit
Is it possible to scale button image? can't find a way to do it
mmm ok, not sure if there is a better way but I just made image and text blank and added two child elemets: lable and visual element (for image)
does anyone know how he is doing this? at 2:51
serializing an abstract class
https://youtu.be/VXpG_Z0YTaI?si=I8biu3fDEr8wI_2p&t=171
You can't serialize an abstract class.
ok
just trying to do what is done in the video
listen for the full 9 seconds
3:10 or so
I did but didn't understand
Unity's serializer does support abstract types if they're derived from UnityEngine.Object. In his video, those things he's putting in the list are derived from Item, an abstract MonoBehaviour
the typical use case is serializing abstract MonoBehaviours or ScriptableObjects
Is there a way to debug log in multiple console ?
Like having my logs of my player and ennemy in separate console
Maybe using a custom inspector window is the solution
So if i get this right, using .SetActive for UI objects is very bad, but for other stuff like 3d objects in game it's not a problem?
Why is SetActive for UI objects bad ?
probably because canvas needs to recalculate things and reorder things
it's not like "too bad avoid at all costs", just not super optimal... which is something that may not matter at all, unless you do it quite a lot
I have not noticed any perf problems from that specifically
custom editor using 2 UIToolkit ListViews
ty ill try
guys when i animated by 321 go for a car game, the go letter never disappears and just stays there, can someone help
show code
i wanted to try the example given at the ListView class, i got a few methods that arent regnized
such as
i didnt create any asmdef so i shouldn't have an issue with a missing asmdef
where did you see this?
the code ?
yes
I suspect the example is outdated, the Events section of the docs does not mention an onAdd or onRemove event
mh
well thats not cool, ill try to make it myself or find another example
ty for trying
makeitem and binditem are all you really need
ok ty
it quite dont understand how those methods works
leftPane.makeItem = () => new Label();
leftPane.bindItem = (item, index) => { (item as Label).text = allObjects[index].name; };
leftPane.itemsSource = allObjects;
the use of makeItem and bindItem looks mysterious to me
why am i making one item ?
how to flip hitboxes correctly in Unity. I am setting localScale to (-1,1,1) but it is giving warning as the BoxCollider have negative scale can have wrong collision?
think of it like a template
1 root and lotta children
I tried flipping hitbox with rotation but the shader no longer shed light on the player because the vertices is on the flip side now
how to fix this?
now i got an issue with calling a method to add stuff in the list used in the ListView
since the class of my custom window is editor, I cant access it in regular code.
How could i make like the Debug class
calling anywhere, no compiling issue when building and stuff
make item should make a visual element which is displayed in the list.
bind item binds a particular element in your list to an item on the display
okay
so, if i change the value of a index in the list, the Label in the ListView should update ?
yeah i just tested
would you like me to send you my ListView template code?
sure
that's the magic of listview
and if you dont mind i would love some directions for making a regular Mono class interact with the Custom WInodw at runtime
or not 😂 .. basically what listview is doing is polling the list in editor update .. not sure why they're doing it like this 🤣
thats easy, make your List which the ListView relies on public and then just add to it from the Mono
its public for the class
but not static, so how do i get the ref to the window class ?
GetWindow
should the mono class be static ?
you an even make your Editor a singleton if you want, even easier
no
okay
there is 12 overload of GetWindow
looks im having issues because the window class is in a Editor folder
so i cant reference the class in other class that arent in the folder
should work
MyEditor window = (MyEditor)EditorWindow.GetWindow(typeof(MyEditor));
MyEditor will not be found because its not in the asmdef file
because its Editor folder
do Destroy(theGameObjectYouWantToDestroy)
thanks
if its not static, this means i have to create a debug log class reference ?
so its not like the Debug class
best thing would be a an own class (MyLog) with static method Log
then you can do
using Debug = MyLog;
okay
as a general rule of thumb,
use/make static methods when the function does not rely on or modify any information outside of its arguments.
Use a singleton when you need a class where there is a reference to a single one unique instance, which can modify its contents. But there will never be two of them.
well now is still miss the communication between this custom debug class and the custom window
Debug classes should usually be static
because Debug classes should only contain methods that do not rely on or modify any information outside those debug methods
if you have a debug class that is not static, I need to question wtf you are doing
well, i am using a listview in the custom editor, so the custom debug class should add an item in a public list that is inside the custom edutor
the issue is that the custom window class is in an editor folder, so i cannot reference it in my custom debug class
also keep in mind that modifying static fields is extremely dangerous, so you should extremely rarely even define them
i am not modifying a static field
that is just general advice on this topic
so i don’t tell you to make something static, and then you go and make a bunch of static fields etc, and then make your life difficult
can you not make a reference to Assembly-CSharp Editor in your asmdef?
i don’t think you are supposed to do that
i made an asmdef in the root of my assets folder, which defines an assembly that functions equivalently to assembly-csharp
then add asmdefs etc in subfolders to break it up
i didnt create any asmdef
i think its unity that makes all classes in Editor folders to a special editor only asmdef
wait, let me see if I can put something together real quick
@round violet you can perhaps make an event in CustomDebug that you fire whenever you log, and make the Debug Windows listen to that event?
could be a static event
it will
because it doesnt know the class exists
Editor stuff knows about non-Editor stuff
your Editor class will know about the other one
hello
polietely ask it to refresh? 😄 sorry, I haven't used it much and have no idea about that
ill see if there is any method to do that
well now my window is super small so i cannot resize it
all fixed, ty everyone
@knotty sun in case you are still doing your thing
Hi guys. How can I delete or prevent gameobject under dontdestroyonload to don't be destroyed as I wanted in a specific stage of my game to destroy them and change to another scene
I don't understand your question. Objects in the DontDestroyOnLoad aren't destroyed when you load a new scene in "single" mode (the default)
Are you asking how to move objects back out of the DontDestroyOnLoad scene, perhaps?
yeah
My first suggestion would be to not use DDOL in the first place
why not just destroy the objects manually?
Do you want to move something out of DDOL scene, or do you want to destroy it? And do you have a reference to it or?
otherwise, you can move objects from scene to scene
But I'm not sure why you'd want to do that here
If you want to destroy everything in the DontDestroyOnLoad scene, then I'd suggest changing your design so that:
- You keep references to these objects, OR
- You put these objects into a scene that you unload yourself
You could look into Additive Scene loading, if the goal is to have things persist between some scene changes and get unloaded in other scene changes
yeah -- this is the way to go if you have a bunch of objects that need to get loaded, stick around for a while, and then all unload together
I am using DDOL as I have a websocket singleton and I don't want it to disconnect from the server until now that I want it to disconnect from the server and delete the object to like restart the game without closing the app
Just destroy the object, then
All that DontDestroyOnLoad() does is move the object into a special scene that never unloads
it's not DontDestroyEver()
yeah that is what I was trying to destroy all the objects inside the ddol but I didn't success
Does it have more than that websocket singleton? (I'm not sure why it needs to be a Mono in the first place, but I'll assume it does)
Generally you can do something like someDDOLobject.gameObject.scene.GetRootGameObject().ForEach(go => Destroy(go)); to kill them all
but that's... quite barbaric...
If there are multiple objects, just keep track of all of them
okey I'll try thanks
destroying everything in the DDOL scene seems like a terrible idea
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Stop spamming.
Posting the same thing to more than one channel is spamming here
especially when it belongs in none of the channels
Also, that kind of post is not allowed, as you've been told
"We do not accept job or collab posts"
I have a problem with circle position on object
float rayDistance = 2.5f;
Ray ray = new Ray(Camera.transform.position, Camera.transform.forward);
Debug.DrawRay(ray.origin, ray.direction * rayDistance);
if (Physics.Raycast(ray, out hit, rayDistance))
{
if (hit.collider.gameObject.CompareTag("Tree"))
{
TargetPrefab.transform.rotation = hit.collider.transform.rotation;
TargetPrefab.transform.position = new Vector3(hit.collider.transform.position.x, hit.point.y, hit.collider.transform.position.z);
TargetPrefab.transform.localScale = new Vector3(hit.transform.localScale.x, TargetPrefab.transform.localScale.y, hit.transform.localScale.z);
TargetPrefab.SetActive(true);
if (Input.GetMouseButtonDown(0))
{
}
}
else
{
TargetPrefab.SetActive(false);
}
}
else
{
TargetPrefab.SetActive(false);
}```
what is the problem?
I have a problem with circle position on object
and the problem is? 🙂
the position is not aligned with the rotation, i.e. where I have it selected with the mouse, a circle should appear in the center of the object with a given y position and it should work with rotation
Hi, so I have a problem with the spawning my menu, I want my menu to spawn at my cameras location plus an offset when I press escape, here is the code:
"escMenu" is my menu, and teh script is part of the main camera. My menu ends up spawning at teh coordinates the prefab is located. Why is this, and how can I change this, thank you for any help in advance!
i got a drop down but for some reason i cant select Cable
int index = 0;
index = EditorGUILayout.Popup(index, options);
if (GUILayout.Button("Create"))
{
InitList(options[index]);
}
so you need something like... TargetPrefab.transform.position = hit.collider.transform.position + hit.collider.transform.up * Vector3.Dot(hit.point - hit.collider.transform.position, hit.collider.transform.up) 🤔
@round violet Got it kinda working but it's not perfect yet. I'll contine working on it then send you the code
but basically the problem is that you're only moving it on the world Y axis, not on the local Y of the hit object
i got it all working man !
i @ you earlier to tell you that :(
no i feel bad because you worked on it
Thank you, it works
missed it, don't feel bad, I need this for myself anyway
public class CustomConsoleDebug : EditorWindow
{
private Dictionary<string,List<string>> _data = new();
private ListView _listView;
private string ConsoleId = "";
//private static Dictionary<string, EditorWindow> _windows = new();
private string[] options = new string[] { "Player", "Cable"};
[MenuItem("Custom/Custom Console Debug")]
public static void ShowWindow()
{
EditorWindow window = CreateInstance<CustomConsoleDebug>();
window.titleContent = new GUIContent("New console");
window.Show();
}
void OnGUI()
{
if (ConsoleId.Length == 0)
{
int index = 0;
index = EditorGUILayout.Popup(index, options);
if (GUILayout.Button("Create"))
{
InitList(options[index]);
}
}
}
public void InitList(string id)
{
titleContent = new GUIContent("Custom console: " + id);
ConsoleId = id;
_listView = new();
_data.Clear();
_data[ConsoleId] = new List<string>();
_listView.makeItem = () => new Label();
_listView.bindItem = (item, index) => { (item as Label).text = _data[ConsoleId][index]; };
_listView.itemsSource = _data[ConsoleId];
rootVisualElement.Add(_listView);
CustomDebug.LogAction += AddData;
}
private void AddData(string key, string text)
{
_data[key].Add(text);
_listView.RefreshItems();
}
}
public class CustomDebug : MonoBehaviour
{
public static event Action<string,string> LogAction;
static public void AddDebugLog(string key, string text)
{
LogAction(key,text);
}
}
use :
CustomDebug.AddDebugLog("Player","moving");
prob not good because it has one dict for all data
but for know it works
that's cool, glad it's working for you
well its partially working because i cant select other options in my dropdown
move this to class level
int index = 0;
worked ty
damin i forgot dicts doesnt serialize
have to add some init dict code
is there a GetWindow but for all windows ?
don't think so
the event action is only bind on creation, so when reloading i have to bind it again
you could do it via reflection though
one problem I see, your system only works when the editor window is open
well yeah, since if there is no listener the action errors
action shouldn't error! hey!
but i will always have my windows open, and if not, ignore the debug
no reference error
LogAction?.Invoke(key,text);
instead of LogAction(key,text); ?
yes
try using a Queue
i still need my window to bind again after compiling
you can make something on the editor side that stores the messages as they come and is always subscribed
Lot's of ways to do this, I'm gonna make a generic plugin coz Unity Console sucks
Am curious to see! I've thought of doing that, but never got to it. I wanted to be able to ignore messages by some patterns and stuff like that 😄
exactly filters like the Android LogCat package
so actions arent serialized
Anyone able to assist? This happened last time I tried this
RaycastHit[] leftHit = Physics.SphereCastAll(leftHand.position, 0.05f, (leftHandTarget.position - leftHand.position).normalized, 5f, handInteractableLayers);
if (leftHit.Length == 0)
{
leftHand.transform.position = leftHandTarget.position;
}
else
{
foreach (RaycastHit hit in leftHit)
{
Debug.Log(hit.collider.name);
}
}
For whatever reason this is finding objects half way across the map despite the fact the surrounding area is empty
It's aiming from an empty transform to an xr controller and hitting the floor? The only time it hits the controller is when the controller is higher than it
Keep in mind the controller is way above the floor and almost on the same y level as the controller
My IDE shows Unity methods in blue, which is weird. Is this happenning due to some setting?
That just randomly happens it happens with VSC too it's weird
is the same for me 🤷♂️
on mac, this never happened to me.
Unity methods are highlighted in blue custom methods are yellow
and it's super weird
Always been like that for me since 2019 ¯_(ツ)_/¯
yeah, I assumed it's the default and didn't care too much, but an option might exist - google ot chatgpt should know! 😄
show the scene and draw a line where you expect the cast to be
I found out the issue and it was a bit of a stupid one... I turned the player layer off in the layermask so it wasn't hitting anything and carried on sweeping. Making the distance the distance between the xr controller and the hand worked
Now my only issue is once the spherecast hits something it cant actually come off of it because it's constantly hitting it
not sure what that means
So the spherecast's origin is the leftHand position. If it doesn't hit anything it moves to the XR controller
But the issue is it can move to the controller and touch the ground
And when that happens it's stuck in a loop of touching the ground
Sorry if my explanations suck I don't really know how to explain it
can i make action listening to a specific arg
for example :
i have multiple instance of MyClass
each one have an id
when invoking the action with a param, if the given id matches an existing id in the instances of MyClass, then call the action of that instance
Why is this happening?
I tried to add this component ladder on the FPScontroller
i think you need to implement your own one
btw if the objects know which specific arg they should listen, then why not having an dictionary
Dictionary<value of the special arg,List<the objects>>
```then the publisher calls method of the objects in the list and passing other args, you dont even need event
or just early return
Is the CLASS called Ladder
are you replying to me?
yes
this file i the one i wanna add on FPSController
no, not reply to you
The class, not the script
Can you show the code?
ndk 21.4.7075529 detected. unity requires NDK r21d(64-bit) (21.3.6528147). how i can fix this error
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class Ladder : MonoBehaviour
{
public Transform playerController;
bool inside = false;
public float speed = 3f;
public FirstPersonController player;
public AudioSource sound;
void Start()
{
player = GetComponent<FirstPersonController>();
inside = false;
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Ladder")
{
Debug.Log("TouchingLadderTrue");
player.enabled = false;
inside = !inside;
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Ladder")
{
Debug.Log("TouchingLadderFalse");
player.enabled = true;
inside = !inside;
}
}
void Update()
{
if (inside == true && Input.GetKey("w"))
{
player.transform.position += Vector3.up /
speed * Time.deltaTime;
}
if (inside == true && Input.GetKey("s"))
{
player.transform.position += Vector3.down /
speed * Time.deltaTime;
}
if (inside == true && Input.GetKey("w"))
{
sound.enabled = true;
sound.loop = true;
}
else
{
sound.enabled = false;
sound.loop = false;
}
}
}
Ok cool. Good
Do you have compiler errors in the console?
I think there was one yellow text error and I pressed ignore or something and it has now disapeared.
can i go back and see it? is there any way or should i just try to undo history and try to un-import and import these assets again to see if there's an error in them?
I can't undo the import though
How do different mechanics work at different levels in the like Pummel Party game? Does anyone have knowledge about this? Or can you help me with which keyword to research the subject?
A compiler error wouldn't disappear, so if there is nothing there now, you are fine
so why can't I add this little ladder script on to my FPS controller?
oh, wait, you mean this?
Yeah, if you click that, the console would open
And yeah, you have at least 1 compiler error
That is why the script can't be added most likely
when I call playerInput.Gameplay.MousePosition.ReadValue<Vector2>();, this normally works to get the current mouse position. but if I click off of the gameplay area, and then click back into the gameplay area, it always returns Vector2.zero. Any idea why?
oh wow, I actually got more with where that came from
Btw can I turn the ladder script into python? because I don't understand shit in C++. 😦
I was told you could use these scripting nodes similar to those they have on blender or unreal engine 4 where you connect the nodes and thats how you basically go on without any code. Or that you could code in any language but I dont know how to do that here.
- unity doesn't use c++, it uses c#
- no, not a good way to do python afaik
Yes, there is visual scripting, no you cannot code in any language
https://learn.unity.com/project/introduction-to-visual-scripting
I recommend against visual scripting though, because it is honestly more work and you have to understand coding anyway
The issue with the errors looks to be that you imported stuff twice.
It is saying that there are multiples of all those scripts
so does that mean it's already in FPScontroler?
imma try running it to see if he can actually climb ladders and stuff
No, it means you have the assets you imported twice
Ladder is most likely NOT on the fpscontroller
Yes. The game cannot run until every red compiler error is removed
You have to go through the project window and remove all the duplicate files
I searched "ladder" on the assets and I only got this one scripting file of C#, nothing else. The other 3 files seems to be something else..
sound and icon.
Ladder has nothing to do with the issue
It's the other assets
Sway, CameraUIZoom, Flashlight are the first three errors
It's all stuff in the PublicSeriesFolder folder
those are also creating an error?
ok you know what
imma delete this entire folder and only upload each file seperately whenever I need it cause this seems like it would never work otherwise
Those are the only thing causing an error
Ladder has no errors
The other errors are just preventing that script (or ANY script) from being added
maybe these scripts are stored inside of the FPS controler?
There is a difference between assets and components on a gameobject or prefab
The issue is with asset files
Not any gameobject
So the problem seems to be here?
No
In the project window only
It has to do with assets, not gameobjects
FPSController has nothing to do with this issue
Go into that folder, find duplicate files, click one of the two, hit delete on your keyboard
I meant to circle the word project btw, not the search for ladder
oh ok gotcha
do we have any idea how can you quickly find any duplicate files?
cause there's like a million files here
Maybe delete the entire folder and just import it once
Yes
That is normal, and necessary
Is there any good reason to ever use SendMesasge in a medium sized production project? I saw this in an asset I imported and had to research what it's for, and I can think of many other ways to accomplish the same thing? (I think I saw send messages in the new input module player input, so maybe I am using it anyway?)
Ok so I deleted the 2nd asset package
I only kept these and i still get these errors
this is so confusing, i love it
There's no reason ever. It's an extremely sad approach. (Inefficient, uses strings...)
in VS for mac, my TODO were always bright purple. Would anyone know where that option is for windows?
TODO?
yes
did that not normally become purple for you if you write TODO in a comment?
that just happened for me out of the box on mac
Ok cool. These are not errors. And the self-intersecting ones can be ignored afaik
Just means the creator of the models did not clean up properly when exporting
oh yeah never noticed on vs mac lol
no built in way ig
there's this https://learn.microsoft.com/en-us/visualstudio/ide/using-the-task-list?view=vs-2022
but no coloring
ty. I'll give it a shot
one of them would not install. went through extensions tab in VS to find something that might be promising
Isn't VS for Mac dead?
no longer supported, but for the year I've been using it, it was good
Might want to switch to Rider or VS Code soon.
{
public class Attack : Action
{
public Transform killer;
public KillerChase killerChase;
private bool isAttacking = false;
private bool isDead = false;
public FogOfWarRevealer3D revealer;
public override void OnStart()
{
killer = GetComponent<Transform>();
}
public override TaskStatus OnUpdate()
{
Character.Survivors.Survivor survivorComponent = killerChase._target.GetComponent<Character.Survivors.Survivor>();
if (survivorComponent == null)
{
return TaskStatus.Failure;
}
PlayerStatus status = survivorComponent.playerStatus.Value;
if (status == PlayerStatus.KnockedDown)
{
isAttacking = false;
isDead = true;
revealer.hidersSeen.Clear();
return TaskStatus.Success;
}
RaycastHit hit;
if (Physics.SphereCast(killer.position, 4f, killer.forward, out hit, LayerMask.GetMask("Survivor")) && !isAttacking && !isDead)
{
isAttacking = true;
Debug.Log("Attacking");
if (status == PlayerStatus.Injured)
{
survivorComponent.playerStatus.Value = PlayerStatus.KnockedDown;
}
else
{
survivorComponent.playerStatus.Value = PlayerStatus.Injured;
}
return TaskStatus.Running;
}
else
{
isAttacking = false;
return TaskStatus.Failure;
}
}
}
}
can someone help pls? the action keeps running even after the survivor is knockedDown
I'm using behaviour tree
animation override breaks the rolling animation for whatever reason
Nobody is going to do free work for you, no.
Sure.
is there a method to search for all components of a given type? Slow is fine, because this is for editor mode.
is public static T[] FindObjectsOfType(bool includeInactive); the recommended way?
Im alive
i love your mood bro
Anyone having any problems with Unity Editor 2022.3.20f1 with EditorApplication.delayCall: UnityEditor.Sequences.SequenceIndexer.InitializeWithExistingData when recompiling?
Currently, it takes 1 min and 30 secs running that command after script compilation.
is it possible to do like a timer or something, i have a flashlight and want its battery variable to decrease every 3 seconds. I tried with Task.delay but not working it just ignores it
Just use a timer variable
float timer = 0;
float interval = 3;
int batteryLevel;
void Update() {
timer += Time.deltaTime;
if (timer >= interval) {
timer -= interval;
batteryLevel -= 1;
}
}```
If the battery level is a float, you can subtract Time.deltaTime * (1/3f) directly, to have a decrease of one third per second, or 1 for each 3 seconds.
thank finally i got it as a beginner i was struggeling with this for hours
@orchid abyss For the record, this response: #archived-code-general message was to a deleted message, not your question
is there any way that i can play/preview animations in editor via script?
Hey Everyone! Can someone explain me why I can't generate lightmaps? I made sure to create a light profile under the scene category so that won't be the issue. Thanks!
Are you currently in play mode?
these errors confuse me
customDrawLogic is a singleton that should be destroyed when I swap scenes. Everything works fine. But when I come back into the scene, objBase.customDrawLogic is null (unity null, it's a destroyed object)
but when I follow debugger, it just skips that whole if statement! even though it is null!
Seems like the field is of type ICustomDrawLogic which is an interface type
I suspected it is interface-related
since the interface is not a derivative of UnityEngine.Object, it will not use Unity's overridden == comparison
so it will be checking against true null
Correct.
I see, which is why it skips
you could do:
if (objBase.customDrawLogic is UnityEngine.Object uo && uo == null)```
that is smart. I'll give that a shot
yeah, throwing in "as Object" made it all work.
thanks
Is there a mechanism to throttle the rate of events? I need to use this in many places. Player smashes the keyboard but I only want to process X keystrokes per second. Same for object spawning. See it like a network bandwidth limiter on a firewall.
you would need to add your own logic for that tbh
object spawning should just have a cooldown. that does not mean you should filter player input
Yeah you'd need to write your own code to do it, it's not too complicated. Besides throttling, there's also debouncing.
you should always envision the player inputting the worst possible combination of inputs, and the game logic should be able to detect everything, but still react properly
gotta always put your game through the "cat on keyboard" tests
pause buffering, a goddamn turbo controller, smashing your face into the whole keyboard at once… the game better still work
I had a project to create a shell and one of the tests was the instructor basically smashing their hands onto the keyboard to check if it crashed
good instructor lol
one thing i need to do is write an input fuzzer that just fires a massive pile of random inputs at my game
random stick positions every frame, 0.5x A presses, the works
one pattern I do is to put integer locks on things like pausing.
public void RequestPause() { pauseRequests++;
if (pauseRequests == 1) SetPause(true);}
public void RequestUnpause() {
Debug.Assert(pauseRequests > 0, “Can’t have negative requests!”);
pauseRequests- -;
if (pauseRequests == 0) SetPause(false);}
you’re basically storing the number of things independently interested in (un)pausing, and only doing it once no individual service is requesting the game to be paused.
oh yeah, this is a good idea
the other is the timestamp method, which i’ve shown before, which is very good for buffered inputs
I've done quite a lot of "reference counting" in my current project at work.... so many things that can be requested by several completely unrelated things at any time
At some point I started using RequestSomething(Object requester) and putting those in a hashset... to allow detecting of who wants access, who releases access, for when we have issues with something requesting a thing, and another one "releasing" it
or for when we wanna give more freedom to the requesters to be lazier 😄
I'm refactoring all of my movement code and I'm trying to make it future-proof. What is the best way to implement a state machine? Should I have one class essentially dedicated to taking a bunch of variables from all over the place and outputting a state? I will have a state for movement based upon position (grounded, in air, etc) and a state based upon combat status (stunned, slowed), etc
you can pretty much 1:1 the animation blend tree's statemachine or get an idea from that
I’ e done this several times. My advice is to make these separate classes:
- Player movment. This primarily uses an enum to represent player state (like idle, jumping, swimming)… It updates this enum based on player inputs and:
- Player contact state. This class gets read by playermovement for logic, but it gets filled by:
- Contact checker. This determines player grounding state, if you’re on ice, etc. And puts that info into ContactState.
- Player animation controller, which reads the enum in playermovement (and whatever flags) to know what to show.
- Player logic for reading contact state and other stuff to know life/death/HP etc
- A movement stat scriptable object to just hold values for things like run speed, jump force… just settings. It keeps playermovement much simpler.
one thing that makes player movement really bloated and overcomplicated is to try to do everything in it
I've got a PlayerController -> Motor class to separate the input from the state logic a bit more instead of bloating it into a single script
i’ve seen a lot of PlayerMovement scripts that handle player HP, animation state, ground check, and player movement…. it always ends as a trainwreck
player movement gets complex. stuffing all that shit into it is a terrible idea
also, more bools more problems
bools are like juggling. a few are ok. 20 is not ok
can always do bidirectional references so you can always grab references from the top level
instead of deriving too deep
or bloating single scripts
otherwise events
i try to make it more like one after the other.
contact generator fills out contact state.
playermovement reads contact state and updates player state enum.
animation script reads player state.
I think I would want a class that determines position state, sends that output to movement state and combat state. The messy part is when movement states and combat states interact with each other both ways
yeah you're right, fighting state should already be pre-calced based on prior frames
and updates can be made on the current frame too ofc
then send that all to movement state
yeah, just make sure to stage it
what does that mean?
do not have player movment updating player state before and after animation script reads it
stage 1) generate contact information
stage 2) determine player state
stage 3) determing output logic
do not be updating info from 1 in the middle of 3
1 feeds 2 feeds 3
ah yeah, I plan on having all the states finish their calcs and then sending the info to executing player movment, animation updates, server updates, etc...
Hi! Do anyone know what is wrong with this script?? I want it to add 1 if there is a game object with the tag "Farm" in range but it starts adding up infinitivly as long as there is one in the range
Thank you guys
You are not removing the object from consideration on the next update
How do you mean??
You make a list of all farms and then count them all each update
So how should I do??
if a farm is in range you have to remove it from the list and add it to an already-in-range list
But how do I make so that the FindGameObjectsWithTag wont just place it back again?
then check that list if a farm goes out of range and move it to the first list again when that happens
It runs only once
Oh sorry. That is not supposed to be in the start function 😅
Its supposed to be in the update function
But i have to do it?? I have a city builder like game and I have to check if the GameObject is close by or not
i have just explained how you do it with two lists
that is the correct way if you don't want to use physics checks
When I read "in range", you probably want to use some sort of SphereCast to limit the result set to what's close enough
It's less expensive than using Find, at least
It would be an improvement, but yes they need to cache what farms they've already seen in some list
you make two lists, inRange and outOfRange fill them by iterating with whatever your find or overlap returns and range check yields. then iterate them each frame and move them between the lists whenver their respective condition for being in the list changes, whenever you detect such a change, fire your event (your count + 1)
thats how you manually create a TriggerEnter and TriggerExit event.
there is opportunity for optimization but thats the principle you've been missing in your code
@cold parrot Okay i think I got a solution. All I need to do now is to remove i from the array.... which I dont know how to do 😂
you cant remove items from an array, only set them to null, which makes no sense in your case
This is what I need to do
as i said above, fill LISTs with your farms from the ARRAY in start
then iterate the LISTs in update and move items between the lists
(you can use HASHSETs for better performance)
How do I move items between lists then?
remove from one, add to the other
but you said that I couldnt remove an item from a list
you cant remove items from ARRAYs
arent lists and arrays the same thing??
no
Can I use lists in the same way as i use Arrays in my case??
no
internally a list automatically maintains a gapless array of variable size
but that is irrelevant here
array is fixed size and has no add/remove
list is variable size and has add/remove
But I dont really understand how lists are going to help me if I cant use them in the way that im using arrays. Can I make so that the for loop skipps items from the list??
yes
You can add to an array though
Of course you can
You cannot
You can place a value at an index
Which is not the same as adding, and it is the key difference here
isnt it?
if you refuse to read and understand what i've explained to you 3 times now you will never solve this
No. Not even a little. adding resizes the structure
The thing is that i don't understand what you are saying.
Use a list.
That is what they are saying
And I want to know how
There are tutorials for that 🤷♂️
You use add and remove though, as they said
This killed my whole plan so now im on step one again
How? That makes no sense
Changing from an array to a list is not that big of a change
Okay. I will look into it
I had a plan on how I would do this as I dont understand a word of what @cold parrot is saying. But that plan dosnt work now
But I will look into it
Thank you
@tribal coral
List<GameObject> _inRange = new();
List<GameObject> _outOfRange = new();
void Start()
{
GameObject[] farms = FindObjectWithTag("Farm");
_inRange = farms.Where(it => Vector3.Distance(transform.position, it.transform.position) <= maxDistance).ToList();
_outOfRange = farms.Where(it => Vector3.Distance(transform.position, it.transform.position) > maxDistance).ToList();
}
void Update() {
for(int i = _inRange.Count -1 ; i >= 0; i--) {
if (Vector3.Distance(_inRange[i].transform.position, transform.position) > maxDistance) {
_outOfRange.Add(_inRange[i]);
_inRange.RemoveAt[i];
}
}
for(int i = _outOfRange.Count -1 ; i >= 0; i--) {
if (Vector3.Distance(_outOfRange[i].transform.position, transform.position) < maxDistance) {
_inRange.Add(_outOfRange[i]);
_outOfRange.RemoveAt[i];
}
}
// your count is just _inRange.Count
}
Hello! I have animations for a walk cycle for a character right now in unity (haven't messed with the controller yet I'm nervous of messing it up) but I'm not sure how to apply these animations to the player movement script I already currently have. I can send the script if needed but I'm not really sure where to start looking bc just trying to look it up on forums is confusing to me (I am,, really not good at coding)
share script
oh! ok sorry I thought I was in that chat
Ok, so I wrote my own rate controller. Since I was worried about key clashes, I used LINE + FILENAME as unique keys. Is there a better way to get unique keys in C#?
Basically something better for GetKey()
But you would have to store the Guid to check the rate in the same line. What I like is that the code is really bound to the specific line.
but typically you'd just make a request against the limiter and return a handle which can be a monotonic integer you just increment on each call
use handles
using a monotonic integer for rate control doesn't include time, does it?
its just a handle
so the caller can pass it back on subsequent checks, identifying the timer it has claimed
you internally associate the handle with the call & timer
That's unfortunately beyond my C# knowledge. As you might gues from LINE, I did mostly C. So I unfortunately don't fully understand what you mean.
well if you know C, handles should be your bread and butter 😄
Wasn't sure whether you meant the same as for C#. I saw an implementation online, but the problem is that delayed actions can occur when the original object is already destroyed.
anyway, in C# you'd likely make an instance of a rate limiter for each resouce you want to limit access to and just have the user check that instance
But you need a spearate variable for storing the reference. That's what I like about my implementation. It's generating a globally unique key (filename+line) and uses that.
So less code. Less space for bugs.
your rate limiter should not be handling the action, it should just block or reject access
think of it as a sync primitive
