#archived-code-general
1 messages ยท Page 361 of 1
Hmm, not completely sure how you could do it through a Editor script, maybe this could help: https://discussions.unity.com/t/how-to-save-screenshot-of-editor-window/485328/3 - it sounds like the idea is to create a new Texture2D during the Repaint phase of the Editor window
Better be consistent, if you use the same IO methods on both sides, the code is easier to understand
yea i guess it so but the real problem is i guess when u take screen shot from game view u can dynamicly change size of the gameview and u can route that pixel data to renderTexture etc therefor we can take a hight res textures with api but in editor size there is not because the size of editor rect is stable and fixed idk how can i do that but i will try xd
what is the difference between ObjectPool.Dispose/Clear? cant find any documentation on it. Also, does anyone know what could be causing a null reference exception when clearing an object pool during a scene change?
there is literally no difference as Dispose just calls Clear. that exception means that something in the pool was likely actually destroyed rather than just being released to the pool
okay, but I am trying to Destroy everything in the pool as well
not just release it
is that not what Clear does?
my point is that you destroyed something that is in the object pool prior to calling Clear
i see
one way this could happen is if your objectpool is stored on a DDOL object but the pooled objects are not and you switch scenes. naturally everything that isn't DDOL will be destroyed
why not clear it before you switch scenes?
or just create a new objectpool instance so the old one gets GC'd
well it's subscribed to SceneManager.sceneLoaded
so not sure the order
I will do that
sceneLoaded is called when the new scene is loaded, so naturally that happens after the old scene is unloaded and all of its non-DDOL objects are destroyed
got it
Hi there!
I had some code that changed a sprite alpha. It worked all right.
But I created some animations for this gameobject that change the color of the sprite.
This animations are not played at the same time that the code changes the color.
But i'm guessing once you tweak the color of the sprite renderer from an animation, you cannot change it through code anymore (the same happens if you change the scale through animations and code, the code tops working)
Can anyone tell me if this is right? Also, is there any way to avoid it?
that is correct. you can avoid this by controlling the sprite renderer's color in only one place rather than on both the animator and in code
if an object gets destroyed from loading a new scene, is it removed from the object pool as well?
or do I NEED to make a new instance to remove all the null references
no, why would it be? the object pool has no knowledge of scene loading
haha i hate this way to avoid my problem. I want to use both T . T
Thanks for your answer โค๏ธ
do I have to reset the dynamic font asset when the game is closed?
{
MoveDirection = Orientation.forward * VerticalInput + Orientation.right * HorizontalInput;
if(OnSlope())
{
rb.AddForce(GetSlopeMoveDirection() * MoveSpeed * 20f, ForceMode.Force);
}
if (Grounded)
{
rb.AddForce(MoveDirection.normalized * MoveSpeed * 10f, ForceMode.Force);
}
else
{
rb.AddForce(MoveDirection.normalized * MoveSpeed * 10f * AirMultiplier, ForceMode.Force);
}
}```why does it stop very abruptly when i touch a wall while i'm pressing a,w?
What are you expecting to happen? Wallrun?
no
Are you going to elaborate? Lol
You aren't expecting to either wallrun (keep moving along the wall) or stop abruptly, so what do you need instead?
I don't want to do Wall Run, I just want it to run and walk, but I don't know why when I touch a wall when I press a, w or d, w it stops abruptly as if there was a wall in front of me.
First I'd try creating a PhysicMaterial with low friction. Maybe set dynamic friction to 0
Then assign that to the rigidbody
And maybe set friction combine to min
Ok I'll try that, thanks
at what point would you guys suggest implementing a dependency injection system? is it bad practice to hold some references (root gameobjects for enemies, loot, etc) on a gamemanager?
unity doesnt really have a proper dependency injection system, you can make a basic one or use libraries. Basic ones including using methods or events to pass around the ref, good to make bootstrapper scenes with ddols etc
how do i fix this
whats Horizonal
left to right
Either spell the axis name correctly or set that one up in the settings like the error message says
spelt it wrong mb
yeah i have a bootstrapper scene but im trying to find a better way to get references for the ddols in further scenes. right now im just using FindObjectOfType etc but I don't like it
if its ddol just make it a singleton and use that
wdym
in your ddol, you didn't make singleton ?
maybe use that instead of FindObject
no no thats not what i mean
im saying getting references FOR the singletons
the player, root gameobjects to spawn enemies, etc
ohh I mean if its a singleton just access the instance
there are some objects where i use an event tied to ActiveScene changed or SceneLoaded to pass reference through delegate
i think youre misunderstanding. for example I have my enemy object pool. It needs a reference to a empty gameobject to parent the enemies to. Since it starts in a bootstrapper scene, these fields within the singleton are null until it gets to a certain scene. Right now, im just using GameObject.Find to find that empty gameObject to spawn the enemies on but i dont really like this way since it needs to check everytime the scene is changed
like it works completely fine but I feel it could get messy especially with wrong strings, etc
hm yeah at least i would not use string / Find. where is the FindObjectOfType? mind as well slap that onto it
well its just an empty gameobject so findobjectoftype wouldn't work
i could just make an empty class but eh
i dont like that either
put a component or have something already in that scene hold reference
imo using a component is at least type safe
true
can i override plus minus list view button actions in inspector without touching whole inspector editor things
and they are supposed to what exactly ?
doubt any way to do this without editor scripting
You can create your own reoderable list, although it is going to require editor scripting, as navarone mentioned, theres no easy way to modify Unitys inspector code, although all it does is add and remove from a list, then refreshes the drawer for that list to show the updated element, what other functionality might you need for something like that?
I have a really dumb (probably) question.
So I am currently trying to make save system and I have this setup
[Serializable]
private class CoinData : Data
{
public int value;
public CoinData(int val)
{
value = val;
}
public static CoinData Create(int val) => new CoinData(val);
}
This is strictly just an example/test I have set up that saves just an int value. Essentially my saver/loader saves the Data type - the base class is literally just empty - my thought is that each saveable thing can derive from this to implement what it saves and then pass it through the save function that takes in a Data . all is well, I went through the debugger up until the point where it gets turned into JSON:
string json = JsonUtility.ToJson(data);
File.WriteAllText(dir + fileName, json);
after this writes to the file, instead of writing the derived CoinData class with its value (which I know it has right before writing) it writes an empty Data class and loses the value entirely. Does the JSON parser not support what im trying to do, am I doing something wrong, or am I just stupid. Help would be appreciated, thanks!
Both classes are [Serializeable]
How are you obtaining data?
public static bool Save()
{
OnSaveGame?.Invoke();
SaveData data = new SaveData();
string dir = Application.persistentDataPath + directory;
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
string json = JsonUtility.ToJson(data);
File.WriteAllText(dir + fileName, json);
Debug.Log("Saving Game");
return true;
}
and as of now I am using this in my constructor:
public SaveData()
{
UnityEngine.Object.FindObjectsByType(typeof(GameObject), FindObjectsSortMode.None)
.ToList()
.Where(x => ((GameObject)x).GetComponent<ISaveable>() != null)
.ToList()
.ForEach(saveable =>
{
string id = ((GameObject)saveable).GetComponent<UniqueID>().ID;
idToSaveableItems.Add(id, new(((GameObject)saveable).GetComponent<ISaveable>().GetData(), ((GameObject)saveable)));
});
}
heres the json:
{"idToSaveableItems":{"keys":["93f53778-351b-44de-b203-5f8ee2e3f5f4","08c14717-39a1-4a49-86e4-0d8e4641ded8"],"values":[{"Data":{},"GameObject":{"instanceID":31886}},{"Data":{},"GameObject":{"instanceID":31878}}]}}
Is uhh... ISaveable.GetData() returning a Data, then?
correct
So I think the issue is that if you're serializing a reference to a Data, the only members available are those which exist on Data, even if the reference points to an instance of a derived class.
There might be a way to make it work using generics... though then you'd need to know the type of Data from within SaveData() ahead of time... hmm...
so what then make Data generic and then check for each type that T could be or like
damn that sucks ๐ญ
Perhaps you could just have GetData() return the serialized data object?
oh but...
๐ค
yeah it wouldnt be Data anymore lol
im thinking about your generic proposal im not sure kind of approach I could take yet
[Serializable]
public class Data<T>
{
public T data;
public Data(T d)
{
data = d;
}
}
thoughts on something like this
any chance that can get serialized
and then like
public Data<CoinData> GetData()
{
return new Data<CoinData>(CoinData.Create(value));
}
...maaaaybe? ๐
I think that might have the same issue in that SaveData() still wouldn't know the type, since all it knows is that ISaveable.GetData() returns a Data<T>
Nothing terribly clean or concise... I'll play with something for a bit though and get back to you... I reckon someone else may have more useful thoughts on the matter ๐
okay ill play around with it too just @ me if you come up with anything appreciate the efforts
It sounds like Newtonsoft Json.net might be able to handle this sort of generic serialization/deserialization stuff with it's TypeNameHandling.Auto... Though it sounds like unless you include some sort of validation prior to deserialization, it could enable users to instantiate any type by modifying the Json.
Other than that, in my limited C# experience I don't see a way around using explicit types in at least half of the serialization/deserialization lifecycle ๐ฆ
darn ๐ฆ really thought this was doable. Thanks for looking into it I will probably cage it for tonight... all i could find was custom serializer stuff which sounds icky.
guess i will need multiple dictionaries ๐ช
Wanting to prevent user modification is directly at odds with using json at all really
There's zero advantage to a json based approach if you dont actually want users to be able to view and edit save game data, might as well save the space and use binary then
Also as you said, Json.net will handle this fine
I'm not sure if I should be asking it here or in #โจโvfx-and-particles , but seems more like a code question than a particle system setup question...
How do you build pooling system for your particle effects? Or, rather, how do you store and apply particle system setting to particle emitters? I thought you can do it through presets, but it turns out they're UnityEditor and won't be accessible at the runtime.
So I'm not sure how to proceed, either I'll need to make a separate pool manager for every. single. visual. effect. in the game, or just say "fuck it" and instantiate game objects from a prefab ref each time, like a dirty peasant.
Neither feels like a correct solution.
Oh, absolutely ๐
The thought that crossed my mind is that if instantiating any type from such a file is enabled, it may be possible to craft an actually malicious JSON file... For things like save files which players may be inclined to share and assume to be innocuous data, that scares me a little bit.
But admittedly it's still probably not much worse than anything else which they might share
I guess it would probably also require some intimate knowledge of the game logic to actually do something malicious with those types
I'm likely overestimating the threat ๐
I could swear that Json.net actually has guidance onhow to handle this specifically
I know at the very least it throws up a warning if you enable this sort of object creation without some additional handling
Honestly, I never looked into it more than that though. My philosophy is more along the lines of tossing a disclaimer on the splash and then letting people compile text files to C# at runtime if they'd like
I did find some excerpts to that effect which others were quoting, but which I failed to find in the docs. Albeit I didn't dig too much further
Yeah that's totally fair ๐
https://stackoverflow.com/questions/67929193/is-it-possible-to-prevent-the-json-net-typenamehandling-vulnerability-with-a-mar this seems on point
That does actually make it seem like validation could be somewhat more novel than I had in my head
Hey, we are facing a crash on our live game and the stack trace is not really helping point to anything specific. Can anyone help me with which channel to post this query?
Is it possible to rotate 2d Colliders? I'm making a 3d top down game but its actually just a 2d top down game with 3d graphics in disguise, so it only requires 2d collision checking. Would be cool if I could just rotate my 2d collider 90 degrees
You should instead rotate the entire game so that it's on the x/y axis
That is a valid option but I would rather not do so
Then you can't use the 2D physics engine
Nothing else I can do?
nothing that would be reasonable by any measure
for example if i use find property method and add that property auto history methods of inspector will working i mean (CTRL-Z , CTRL-Y etc)
if i add a custom property drawer there is no way to do that i guess do i need to implement also that logics
private void OnValueChange(SerializedProperty property, ChangeEvent<string> evt)
{
bool isInteger = int.TryParse(evt.newValue, out int value);
property.stringValue = GPSelectionData.SerializeValue(isInteger ? value : evt.newValue);
bool needToUpdate = property.serializedObject.ApplyModifiedProperties();
if (needToUpdate)
{
property.serializedObject.Update();
}
Undo.RecordObject(property.serializedObject.targetObject, "property");
}
i made a custom property drawer and use a text field , when i use CTRL-Z on native properties that undo system works well but not for custom ones , so i put a record state on value change callback but when i undo its performed well but there is no graphical changes on property how can i do that
i tried this but not worked after undoRedoPerformed i guess property or serializedObject getting null any idea ?
Undo.undoRedoPerformed += () => EditorUtility.SetDirty(property.serializedObject.targetObject);
Tried to do it this way, but while properties are being copied, I think it somehow breaks the emitter in the process...
Consider switching to Newtonsoft. JSONUtility sucks and you should not use it apart from legacy code
Even if you made a mistake in your code, it is unable to detail the issue and would rather return empty objects. Newtonsoft will actually inform you of the issue if there is one. Emphasis on if there is one because JSONUtility can even fail on correct code
Note by default Newtonsoft serializes properties, not fields. This is default with serializers so you will have to either add a property to serialize, or configure it to use fields.
does anyone know if the .transform call is cached by unity? Or is it like getcomponent. It wouldn't make sense to not be cached
should I make my own cache or is it unnecessary
unnecessary
so it's cached, then?
well, no, not as you are thinking of cached, transform is a C++ object which is referenced by C# code
but there isn't a GetComponent style call - that's my point
no
It forces a transition into unmanaged code which has a small overhead. If you use the transform in performance critical sections where the transform access is the actual bottleneck you can cache it to gain some performance, that benefit is however gone when you write to it. It would only be noticeable in fully data oriented systems that optimize for cpu cache friendly data access.
im getting compile errors on this script :
We can't read your mind
What errors are you getting?
Though, I feel like I know...
how do i check (sorry im new)
First of all, configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
Because the errors are not thrown to you
ohh
Take a screenshot of your console in unity.
Also, if you're new, then #๐ปโcode-beginner
@timber elk if(Input.GetKey(KeyCode.Space) && i == 1)
Is there any difference between these 2 codes?
#if UNITY_EDITOR
if (Application.isPlaying)
{
#endif
Method();
}
#if UNITY_EDITOR
if (Application.isPlaying)
#endif
{
Method();
}
thx
I'll ask this in general I suppose:
I've been trying to optimize my AI recently, as, having 50 Navmesh Agents on screen at once right now, causes Frame Rate Drops. This is mostly due to the amount of NavMesh.CalculatePaths that I'm calling.
public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint) {
NavMeshPath path = new NavMeshPath();
NavMeshQueryFilter filter = new NavMeshQueryFilter {
areaMask = inAgent.areaMask,
agentTypeID = inAgent.agentTypeID
};
if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, filter, path) && path.status == NavMeshPathStatus.PathComplete) {
return true;
}
return false;
}
At the end of the day, my goal is to find a location where the AI can move to around the player, but also, ensuring they can shoot the player from that position. As, my level design could have no path towards the player, but, they could still shoot the player from that location. The current steps I ended up taking, were basically at the start of a level I will build a bunch of "Tether Points" around the world which would update every X frames to check to see if the AI can shoot the player from that location. From there, they check every X frames if they can reach one of those points (Where the code above is.)
The problem I suppose, is, I'm not sure how to optimize it more? As the calculate path call seems heavy.
I guess I could, for example, check to see if the node is apart of the same Navmesh area? Im not sure if thats possible. But the idea being is, if Node A is on Navmesh Area 22, and Node B is on Navmesh Area 23, then checking if they can reach that point is valid. However, if Node A and Node B are both on Navmesh Area 22, there is no point in checking both, as its unlikely they can reach Area22?
Yes. The first one would not compile in a build.
Did you actually do any profiling or are you basing off assumptions?
I've done Profiling, and disabling the CalculatePath causes a massive performance boost.
Can you share the profiling data/findings?
Anything specific you're wanting to see?
Mainly what's taking most of the frame time, how much it's taking and how many calls are made.
Can you expand the topmost update?
Yeah, so the issue is probably not the path calculations
(Nothing else.)
but GC.
I'm not sure what would be causing the GC to build up like that then hmm.
Share the FinisteStateMachine.Update code
void Update() {
if (healthSystem.isDead()) return;
if (currentState != lastState) {
if (lastState)
lastState.Exit(this);
if (currentState) {
currentState.Enter(this);
}
lastState = currentState;
} else {
if (currentState.ExecuteTransitions(this)) return;
currentState.Execute(this);
}
foreach (var item in stateMachineTimers.Keys.ToList()) {
stateMachineTimers[item] = stateMachineTimers[item] - Time.deltaTime;
}
}
One cullprit is definitely the .ToList()
That allocates a list each time.
assuming, stateMachineTimers is a dictionary, can't you just foreach a stateMachineTimers.Keys instead?
Cant when modifying it but I'm sure I can work around it.
Work around it and profile again.
When I do poofParticles.Play();, I want the particles to only play once, I don't want it to continuously loop. For the ParticleSystem, the looping is unchecked. So I don't know why it continously loops:
Hey guys, is it possible to drag an animated object? I have a group parent with 2 sprites in it, but when i try to drag it, it doesn't work, but with static pictures it works
Here is the script:
``
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData) {
Debug.Log("Begin Drag");
}
public void OnDrag(PointerEventData eventData) {
Debug.Log("Dragging");
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData) {
Debug.Log("End Drag");
}
}
``
Using a box collider with 0 on the y scale seems to simulate 2d box collider on a x,z plane
hmmm this might not work, but try setting the duration to something small, like 0.01
Still throwing a lot of GC with
for (int i = 0; i < stateMachineTimers.Count; i++) {
var key = stateMachineTimers.ElementAt(i).Key;
stateMachineTimers[key] -= Time.deltaTime;
}
Though I assume that might be caused by ElementAt now.
why not just iterate over the keyvaluepair?
Yeah. It's probably allocating a list or array behind the scenes as well.
You mean via a foreach?
foreach (var item in stateMachineTimers.Keys) {
stateMachineTimers[item] -= Time.deltaTime;
}
The value can't be modified via that.
Answer me pls
If the animation is animating the position of the object, it will override any changes you try to make.
Child the animation to a root object instead and drag the root object. This may require you to reanimate the child so that it's position is local space.
foreach(KeyValuePair<string,float> pair in dictionary)
{
dictionary[pair.Key] -= Time.deltaTime;
}
doesnt this work? idk if this allocates anything though
It can, the problem is your value is a value type (float), wrap that float in a class and then you can modify it in the foreach
Yeah this was my next thought I was going to try.
Nope, still causing GC.Alloc.
this is exactly what i have done
but it just doesnt work
what is the type of your TKey ?
String.
It is a <string,float> pair originally, and now its <string,class>
and will everything work, if I just skip the allowSceneActivation thing?
that string will be your GC alloc
Tried moving to a full class/struct based system.
foreach (var item in stateMachineTimers) {
item.timer -= Time.deltaTime;
}
Still causing the GC.Alloc.
Did the allocated amount change at least?
It could be more than just that part
After this coroutine is done, the scenes load endlessly and don't switch. What am I missing?
private IEnumerator LoadScenes(List<int> scenes)
{
if (IsLoading)
{
yield break;
}
IsLoading = true;
List<AsyncOperation> loadOperations = new();
for (int i = 0; i < scenes.Count; i++)
{
if (scenes[i] < SceneManager.sceneCountInBuildSettings)
{
LoadSceneMode loadSceneMode = i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive;
AsyncOperation loadOP = SceneManager.LoadSceneAsync(scenes[i], loadSceneMode);
loadOP.allowSceneActivation = false;
loadOperations.Add(loadOP);
}
}
foreach (var operation in loadOperations)
{
yield return new WaitUntil(() => operation.isDone);
}
foreach(var operation in loadOperations)
{
operation.allowSceneActivation = true;
}
Debug.Log("");
IsLoading = false;
}```
Nope.
And commenting out the forloop will remove the issue completely.
change the foreach to a for
And btw, foreach itself might be allocating as well.
Yeah was just about to try that.
Nope. For loop also causes it.
Hmm. Okay, its not from that. Profiler was just, wrong and isn't digging deep enough apparently. Commented out the rest of the code, manually set timers, and no GC.
You mean that the first time it works correctly, but after that doesn't? Or it is stuck with loading endlessly even on the first coroutine?
stuck loading the requested scenes endlessly, previous scene works as normal
I can see them loading in the inspector
operation.progress >= 0.9f instead of operation.isDone didn't fix the issue when list is bigger than 1
it happens with the first corouitne
Yeah so, back to the
public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint) {
NavMeshPath path = new NavMeshPath();
NavMeshQueryFilter filter = new NavMeshQueryFilter {
areaMask = inAgent.areaMask,
agentTypeID = inAgent.agentTypeID
};
if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, filter, path) && path.status == NavMeshPathStatus.PathComplete) {
return true;
}
return false;
}
It appears to be due to the Filter and Path as the leading cause of GC.Alloc. I still have SOME commenting it out, but, not nearly as much.
Kinda sounds like you keep on starting the coroutine.
no. I start it once
Path you can cache as a class field. Filter probably as well.
Log something meaningful when you call load scene.
did you do allowSceneActivation = true
once progress is at 0.9
that's what the code should do, I'd hope, yea
unfortunately can't read the code on mobile
private IEnumerator LoadScenes(List<int> scenes)
{
Debug.Log("Starting loading the scenes");
if (IsLoading)
{
yield break;
}
IsLoading = true;
List<AsyncOperation> loadOperations = new();
for (int i = 0; i < scenes.Count; i++)
{
if (scenes[i] < SceneManager.sceneCountInBuildSettings)
{
LoadSceneMode loadSceneMode = i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive;
AsyncOperation loadOP = SceneManager.LoadSceneAsync(scenes[i], loadSceneMode);
loadOP.allowSceneActivation = false;
loadOperations.Add(loadOP);
}
}
Debug.Log("Loading started");
int s = 0;
foreach (var operation in loadOperations)
{
yield return new WaitUntil(() => operation.progress >= 0.9f);
s++;
Debug.Log(s + " scene Loaded!");
}
Debug.Log("Loading ready");
foreach(var operation in loadOperations)
{
operation.allowSceneActivation = true;
}
Debug.Log("allowed scene activation");
IsLoading = false;
}
2 scenes are being loaded in this example
I'm assuming you're making a loading screen
and it looks like this
ah wait I got an idea...
I'm stupid. It works now
had to move the allowSceneActivation to the previous foreach loop
I don't get why that works but if it does ๐
can someone help me? I have animated sprites in a parent and i have dragging script. when i try to drag the parent, it doesnt work, but it should
it should ? how are you certain
also !ask
๐ข
Is the 2nd method how it's usually done then?
No. What I meant is that it would cause a compile error.
I am sorry, I meant the 2nd one
Yes, the 2nd one is correct
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Got it, thanks a lot!
4 minutes delay
i believe stevesmith helped you in #๐ปโunity-talk did he not?
God I hate GC.
so use c++ and manage your own
he didnt, you must have me mistaken for someone
๐ Been there once. Never again.
I'm using a package from github, but wanted to tweak it a bit so just dropped it's source in my Assets/. The package has a namespace - the rest of my code doesn't. I can use the package code in mine no problem via adding a using statement. But I wanted to add variable of my monobehaviours into one of its definitions and I can't, I'm getting error CS0246: The type or namespace name 'RagdollController' could not be found (are you missing a using directive or an assembly reference?) The external code contains asmdef files (one for runtime and one for the editor part) is there a way I can edit the asmdef's to allow referencing my Asset/Scripts code?
(I think I could move the code into my Scripts directory and remove the included asmdef files, but maybe there's a right way to do it?)
Osteel helped you then
bruh i said it doesnt work
Unity doesn't accept this mesh
and in what way does you saying 'it doesn't work' help us to help you?
wdym by "doesn't accept"?
Says it needs at least one triangle to be valid
show the object you're trying to drag and where you placed the script
Did you assign the triangles/indices array?
So, no then.
hey, im following a tutorial for a natural-feeling character controller. ive copied the code exactly - the errror I am getting is relating to the MonoBehaviour part of the class. The class is public, the name is exact(yes, including capitalisation) and the script editor does not notice any errors. However, Unity won't let me add it to any gameobjects because, aparrently it doesn't derive from MonoBehaviour. Can somebody explain what I'm doing wrong here? ^^; it seems like it should work, but i just can't see any errors. I've copied working code letter for letter and i've checked 5 times, capitalisation throghout the script is exact.
(The script im working on is a custom InputManager script, and I've created a GameObject to attach it to called INPUT, again copying the tutorial to a T. I've done exactly what he's done, yet it isn't working and I don't quite understand why because as far as I can tell, everything is correct)
A valid mesh has to have triangles assigned as well.
I would advise you go through this maybe ?
https://catlikecoding.com/unity/tutorials/procedural-meshes/creating-a-mesh/
show your !code
dyno is asleep or sum
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You would probably need an assembly definition for your own code so that you can reference it in the asset asmdefs.
getting old and senile, like me
hey man the bot is working real hard for a payout of $0 an hour
ok im fixing it
keep reading
yep just saw that part
I don't know if it was different at the time of the tutorial writing, or it's simply a mistake, but you need to define the triangles. Look at the next section of the tutorial.
yes I didn't see that pat
please use links for large code as it was stated in the bot
I'm guessing I would need 2 triangles for a simple square?
Yes.
oh sorry, i didn't realise it was that large. I'm a little unsure how to work it though - give me a sec and I'll fix it
do you have another class named PlayerInput
It wasn't stated in the tutorial, but it was pre-attached when he began recording. He's not shown any other scripts before cracking on with everything else so I'm not too sure. I'm just copying what he's shown
can you link the video
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this tutorial Source Files + Code AND the State Machine version for this project) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
--
Getting a jump to "feel good" is one of the most important things to get rig...
I've just followed the steps he's showing in order
send link to script again, also yeah half the shit isnt even shown..not a fan of that style
still the same issue
sorry, how do I link it exactly? ^^; (im pretty new to text formatting on Discord and such, sorry)
added this
paste the code inside one of the links the bot linked, hit save and send link
Share the updated code..
Yeah so I'm now back to the following code causing the problems:
public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint, NavMeshQueryFilter inFilter) {
// if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, NavMesh.AllAreas, path) && path.status == NavMeshPathStatus.PathComplete) {
// return true;
// }
return false;
}
Commenting out the CalculatePath, the game runs perfectly fine/smooth. Using the NavMeshQueryFIlter which is cached on Start, causes more GC.Alloc to appear than using NavMesh.AllAreas. However, both cause massive performance hit.
probably be better instead of calculating path on each enemy , you have 1 script calculate path for each one
The function gets called via:
public bool HasPossiblePoint(NavMeshAgent inAgent, NavMeshQueryFilter inFilter, AITargetSystem.ShootHeights inShootHeight) {
foreach (var item in tetherPoints[GetHeightModifierAsFloat(inShootHeight)]) {
if (item.canSeePlayer && CanReachPoint(inAgent, item.point, inFilter)) {
return true;
}
}
return false;
}
Where I first check to see if they can even see the player from that point, before checking to see if they can reach it.
ok I fixed the error but this is just a triangle and not a square
I was wondering whether you might want to consider the problem from a different perspective, have the Player figure out where it can be seen from and then tell the AI's this info
I better follow a guide cuz I had no idea how meshes worked prior to 10 mins
would you prefer a specific link? idrk how these work ^^;
Well, the indices you shared earlier are for a triangle. Not a square.
any is fine
https://gdl.space is easiest
okay, thanks for letting me know :)
Thats already handled elsewhere. I use a HiveMind system where that figures all that information out, and is already performant.
do I just paste it and then save it?
OHH i got it
https://gdl.space/xihoxadage.cpp
I think this is it!
?? That wouldn't work. A path from Point A to Point B where each enemy is a different Point A?
yeah .
how about the error message
Did you profile after moving the filter and path to Start? What allocates the garbage at that point?
It wont let me copy/paste text, shall i screenshot it?
(I copy it but nothing pastes but what I previouslt had in my clipboard)
wdym wouldn't work? I do it lol sometimes its better than having a MB on each enemy doing calculations
working now
yea
The calculate path itself causes it. No question at all at this point in time.
I'm just trying to create an 2d box collider on the x,z plane idk if this is an overkill
there might be another script named InputManager ?
Share the profiler data
If an enemy a is in one corner of the map, and enemy b is elsewhere, and they both want to go to the same point, that is a different path...
Also, capture it with deep profiling on.
yes but rather than 2mbs calculating that i found it cheaper 1 mb calculates paths for each
since each instance is another MB that needs to call backend code
Might be wrong, but it seems like they're doing that already.
ohh are they ? didn't see the full code , I just assumed from method but yea does seem to take Agent as param ?
Hmm this sounds good. I will attempt the switch and report back
Yeah, they didn't share the whole code, so I'm assuming here as well.
I just had a crazy epiphany with MB recently through profiling and testing that , eager to share ๐
It seems like HasPossiblePoint is what's allocating. Not the CanReachPoint
Also, it's allocating just 100 Byte. But you're allocating 12.7kb in total on that frame
This isn't even what's taking most of the frame time
There are 50~ of these happening.
Well, there's something really wrong with the way you structured your code and it's really hard to guess from the little pieces of info that you're giving us.,
None of the stuff in this screenshot is taking any considerable time.
You should Share more of the profiling data, sorted by cpu time and/or the gc allocations as well as the relevant code
No idea if I'm being stupid but does anyone see something wrong with this coroutine? When I set my duration to something like 60 it only lasts a second
public IEnumerator SmoothTransitionToZPos(float newPos, float duration)
{
float counter = 0f;
float temp = 0f;
while (counter < duration)
{
counter += Time.deltaTime;
temp = Mathf.SmoothStep(0, 1, counter / duration);
zPos = Mathf.Lerp(zPos, newPos, temp);
yield return null;
}
zPos = newPos;
}
I've never used SmoothStep much so I don't know if it's something to do with that
I tried dividing the deltaTime that was added onto the counter as well but that gave the same result
idk about smoothstep but lerp is wrong
How come?
nvm actually, Mathf.SmoothStep is affecting it so you have to fix that first if its wrong . In example unity uses Time.time
there is a secondary one in the ordinary packages section... do I move the location of the one I've edited? or delete the second inputmanager?
I tried without lerp but it seems to go super fast with that too
Sorry not lerp I mean smoothstep
yeah its not lerp, its smooth step
I don't use smoothstep currently and the issue still occurs
https://docs.unity3d.com/ScriptReference/Mathf.SmoothStep.html
the example here doesnt use time.deltaTime
I suspect thats the issue
show updated code
Literally just this. I'll try to use the method they use in that doc to elapse time though
public IEnumerator SmoothTransitionToZPos(float newPos, float duration)
{
float counter = 0f;
while (counter < duration)
{
counter += Time.deltaTime / duration;
zPos = Mathf.Lerp(zPos, newPos, counter);
yield return null;
}
}
ehh maybe rename yours with F2
never heard of the other one, better safe than sorry though
There are 50 * 140 = 7,000~ calls to Calculate Path right now taking up 0.03ms per Calculation on average. (Some are shorter mind you) which equates to the total 142ms per frame.
I'm not sure what else you're asking to see, but it adds up perfectly fine.
Okie dokie. just looked and I can't delete it anyway, so I'll do that now :)
ah rats can't rename it
https://unity.huh.how/lerp/coroutines
look at this example for lerp
you just put / duration in wrong spot
ur only dividing the time between frame not the accumulated value
So you have 50 of these FiniteStateMachine.Update?
Correct.
I'm asking to see the whole picture. With the profiler data sorted correctly.
why not
is it trying to rename the other one as well ?
it's just blacked out, alongside delete. I moved one elsewhere, deleted it, and then it replaced itself and it's as if it was never removed in the first place
well idk that sounds like something werid is happening, or take a ss of it
and suddenly I'm getting errors now. I missed a semicolon, but it's telling me that there's still one expected on the line? which is so weird? since it's been updated and saved, ONE error is gone, but there's two others from the same line. damn Unity's not been my friend this week. I've failed 3 different setups. I really hoped this one would work.
Lemme get a ss
Okay, then one simple solution would be not to update all the agents every frame. Update one or several of them each frame. But to be honest, that many calls to calculate path are really unreasonable. Might be better to come up with a better system.
It's also likely that the GC is contributing a lot to it. Might want to get rid of that 100 byte allocation.
yes because its part of a Package probably and read only
rename yours instead ofc
but that only renames the file
open the class and rename that using F2 it *should * rename the file too
Which was my original question... Lol I was trying to figure out a better System here.
The goal is to let them find a location that: A: They can shoot the player (Calculated for the entire Level every X frames and is Performant.) and B: That they can reach via NavMesh.
huh... how come it'd let me edit it then? i find that very confusing Unity >:/ (nbh just realising after alot of research Unity has tonnes of non-specific errors and allow things that shouldn't be allowed sometimes lol.)
alrighty, i'll give it a go
yeah idk everyone has different packages, I usually just use namespaces to avoid naming conflicts
it blows my mind how people can use Unity as if it's as simple as reading a book ๐ญ i know one day I will reach that level of mastery, if only Unity had more specific errors and solutions lol
it takes time and experience thats all
eventually you will run into the same issues and you ~~slowly ~~ learn how to avoid them altogether
Removed and same performance.
GOD i hope so. it's now telling me that the class can't be found. I've renamed it, COPIED AND PASTED the name, so I don't know how it can't match. AND it still has these line end errors depiste me fixing that one. god knows.
did you rename the class and did it rename the file ?
can you ss it
btw next time this would be in the #๐ปโcode-beginner section
For starters, you can split the workload into several systems:
- update several of the positions every frame and cache the state of whether the player is reachable/hittable from there. Maybe have a separate list of these positions sorted by most desireable(player is reachable) to less.
- update several npcs every frame. If they need to move to a new position, check if they can get to the most desirable position first. If yes, break the looping and reserve the position.
I did yea, lemme grab it.
Might just pick a different name by adding just a letter or something and removing "player".
The class 'Editor' was depricated in the latest version of Unity (6.0.15), but the link in the release notes as to why wasn't put in. What should we be using instead of deriving from Editor? It's caused havoc in the project from all the editor scripts that derived from Editor. Anyone know how to handle this yet?
you have to rename the script name and the name in the script for a script to work
Then there are game design considerations that could help. For example: enemies shouldn't change their destination while already moving somewhere. That would save you a lot of calls to navmesh.
you have spaces on the actual script name but no spaces in the actual script
that's what I did, that's why I'm confused.
you renamed the actual script in the project window?
OH i fixed it. I had a mistype but the error did NOT specify that the word I had typed was "not an argument" or whatnot. It was talking about the END of the line wierdly enough
I have attached the script to the game object now. Hooray for indirect and non-specific unity errors! /sar /silly
thanks for your help guys - it was probably more than just that and what I was told has also helped for future projects. Thanks so much <3
Not gonna be the last you see of me though lol. Sure i'll see you soon!
I do the first already. The first is if they can shoot the player. This takes my Tether Point count down from 500~ to 140~. So thats already cutting the number of possible points up. I'm also only checking the points that are within Camera View (As they can technically only shoot the player when in Camera View.)
Every X Frames is what I'm doing as well in this case. Though its possible this is bugged looking into it a little bit more right now.
And lastly on your other comment about Game Design: Enemies can change their position, however, only after X seconds. Otherwise, they move, stop for X seconds while attempting to shoot the player there, then move away.
Not "every x frames". "X object updates at most every frame"
Right, you're talking more about staggering them.
I don't know what these 140 points are doing, but if it's heavy, then spread it across several frames, as I mentioned.
Staggering?
Staggering/Spreading it throughout all the frames.
And 140 Points aren't heavy at all.
Even if you update one out of 50 npcs every frame, updating all of them is less than a second at 60 fps. The player wouldn't be able to notice any difference, unless they have access to debug info and see exactly when the decision of each npc is made.
Yeah, spreading through the frames. Never heard "staggering" being used in that context.
Anyways I'm off to sleep.
Found the issue. Probuild 6.0.2 introduces a root namespace 'Editor' which breaks every editor script in the engine. Reverted to probuilder 6.0.1 to fix the issue.
Hey so I have switched to newtonsoft. Everything saves correctly. The problem before was it was saving the Data class as just empty. This time it does SAVE the data correctly, but the data gets lost when it is loaded.
{"idToSaveableItems":{"08c14717-39a1-4a49-86e4-0d8e4641ded8":{"value":66789},"93f53778-351b-44de-b203-5f8ee2e3f5f4":{"value":1423}}}
heres the json that is in the file, but when the json gets converted back into a SaveData this is what I get:
(cc @wide terrace ) #archived-code-general message
At the end of the day, is it possible to check what Navmesh Section a point is on? Take for example these two areas. If a agent is unable to reach the bottom right corner of the navmesh, they are obviously unable to reach anywhere else on it due to the navmesh gap shown inbetween the red and the purple.
If its possible to know if a point is apart of the red navmesh vs the purple one, I feel as if I could improve performance greatly in this case.
This only samples it and returns a point on the navmesh, unless the returned mask returns a different number for each section. This is a singular navmesh in this case, not multiple
i want to implement a third person camera wich looks at the player when moving the camera, it works on the x-axis but not the y-axis... what can i change about my code?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this will return false if the point is not in the area(s) specified
Save/Load system parsing issue
But the area in the red and the area in the purple are considered the same navmesh area. It's a singular navmesh, where it's just one wall blocking it for example.
This is starting to turn into a typical XY problem, it's like you're trying to fight your way out of a paper bag instead of just removing the bag. Take a step back and re-evaluate your whole system and approach to it
Not sure exactly what you're trying to do either but you could use Bounds to see if the point is at this location. Put an object at the center there and a Bounds roughly on the same shape
Basically, the main goal, is to locate a location on the Navmesh that:
1: The AI can move to.
2: The AI can shoot the player at.
The shooting the player I pre calculate globally for all enemies, however the being able to reach the position, I need to check with CalculatePath, which is expensive when you run it over 7000~ times.
does anyone else experience bugginess when using gameobject arrays in inspector? i have to restart my editor whenever i want to add something to an array, is there a workaround?
How do you add them?
Works fine on my device. What exactly is not right for you?
hmm maybe it's caused by some plugin i have installed then, or maybe it's the current unity version i have, either way i get this spam in log and have to restart editor:
Does restarting editor mean restarting Unity?
yeah
And it's not fixed every time?
when i restart the editor it gets fixed, it's some sort of editor bug i guess
Why do you ask the question if it's fixed?
well i have to restart every time i add something to an array it's unusable... it only fixes that one element every time i restart
The majority of Unity bugs are fixed by reloading Unity once
Oh, I see
Please, show the code
Is it a simple array of GameObjects?
it's a public List<GameObject>
The issue is probably in one of your packages
will take a look at packages then, thanks
This answer mentions the version control package
Or try upgrading your editor version too if looking into the packages doesnt work
I would suggest there is a problem with your asset database. Close your project, delete the Library folder and reopen your project, this may take some time
If you're running it 7000+ times often, I'd first see why that happens and put a limit or reduce the amount of logic being done.
Theres not really a way around it unless you can somehow precalculate this too
Thatd imply no collision avoidance on other agents though
tried this, didnt help
which version of Unity are you using?
2022.3.9f1, should i update to a newer one?
definitely, 2022.3 was not stable before .11
why would this code need a comma? Error is telling me Syntax error, ',' expected
[Range(0f, 1f)] public float HeadWidth 0.75f; (From an earlier post in #๐ปโcode-beginner)
0.75f; is underlined red but im not sure what the error is?
did you configure your IDE?
yep, it's underlining and everything now, it's just doing a thing
just compare this line with the one before it. Notice the difference?
Oh. thanks, i missed that. it's not in his code and his doesn't have an error! man im noticing these tutorials must have something that nullifies their errors. it's been like 3 different tutorials that seem to show no errors when they're coding when there are mistakes i've had to correct in mine before
god my mind slipped that
(plus why can't Unity tell me i'm missing an equals sign ๐ญ over a comma)
they either dont have thier IDE configured or they just write it correctly
because. following C# syntax, it thinks you are trying to decalre 2 varaibles rather than one and 2 variables would be seperated by a comma
ahh right.
updating to 2022.3.42f1 seems to have fixed the issue, thanks! ๐
excellent
Having trouble figuring out tweening for my project. I have a camera that zooms in and out on button press using tweening over 0.2seconds (zoomto is a tween call):
Is it possible to get the distance between the Vector2.zero and Vector2.right anchors in local coordinates without reassigning the anchors twice or enumerating through every parent's parent?
I also want the camera to follow the platformer when in platformer mode:
This however doesn't work because if put in update, its snapping to the location mid tween which makes things break. What is the best way to deal with this?
RectTransformUtility you could use I think
I am not sure, are you having troubles with continuously zooming the camera in?
It does not seem to have any suitable methods
oh wait I think I misread what you're asking
Here, I am basically asking how to keep the RectTransform's position same when changing anchors & pivot
not sure what that means, wouldnt you just store it in a var ? then change anchor min and max, assign pivot then use old pos again
I'm aware this is super niche, but I'm kinda just playing around with what I might turn into a package later.
I have a scriptable object that allows you to add elements to a list, and some data associated to each element. They are then stored in a dictionary to be accessed in runtime.
Obviously, later accessing specific things through code by indexing the dictionary by their name is super error prone, and something to avoid. In an ideal world, I would be defining the keys in an enum instead, but in the interest of making it a standalone package I'd like it to be possible to define things with little to no code.
This brings me to: is it possible to use source generators to generate an enum with variants according to the scriptable object? Is this an acceptable solution? Is there a better one?
tbh using a source generator for something this trivial is a bit of overkill
how do I make the texture random
the real solution is this, other techniques like noise-blending also work: https://medium.com/@jasonbooth_86226/stochastic-texturing-3c2e58d76a14
ugh man. So i followed the guys code, completed it. One error.
I'm getting what is said to be the most common of all - "object reference not set to an instance of an object". It has prevented anything I have coded from working.
I have my InputManager(named PInputManager) where the error is supposedly. I will link the code now.
Reminder, I've followed this guy's code exactly. I don't understand what's wrong.
https://gdl.space/paradunojo.cs - PInputManager
https://gdl.space/wusevetimi.cs - PlayerMovementStats
https://gdl.space/xaciwuwoqe.cs - PlayerMovement
I hope it's understandable that I'm confused. Anything I find on this says "Find what's null, find why it's null" but I'm not too sure why it's null. Movement is brought up a few times throughout and VS isn't finding any issues. Whatever this is has completely stonewalled the rest of the code. Nothing works, I can't move the character whatsoever. Shall I just restart hours of work? Or is there a super simple solution I'm not seeing/can't find?
The comments to the tutorial do no good either. nobody else in the comments have had this issue but me
your PInputManager is probably not attached to a GameObject that also has a PlayerInput component
I have attached it, just now. no change
are you reading the first error in your console?
also when you attached it, you did so outside of play mode then tried it again, right? you didn't just attach it during play mode after the error appeared and expected it to magically call Awake again, right?
It's the one and only error on my console.
and it's a habit of mine to stop play mode, and then test after implementing changes, or stop then start again if i've made changes while in play mode. so yes i've tried that too
show the exact error message
also you are following a terrible tutorial if it is telling you to make everything static just to access the values from the input
i just went for one that has the type of controls I'm after
well it's terrible if that is how it wants you to set things up. don't abuse static just for easy referencing
alright, i didn't know, sorry
put this line on line 23: Debug.Assert(PlayerInput != null, $"PlayerInput is null on {name}", this);
i was simply following the tutorial, that's it
which script?
oh wait im stupid sorrry
blind that is
oops i missed a t in the method name
okay no wait it's late and i dont want to mess up any further which script am i putting this in?
obviously the one with the error where you have a PlayerInput variable
i was gonna finish this and go to bed like an hour ago but then ADHD kicked in realising it would just... not be working so im running on a single marshmallow from like 30 minutes ago
alright, sorry
don't make that everyone else's problem. if you are too unfocused or tired to comprehend instructions or debug the issue yourself, then go sleep and come back to it with a fresh mind
i would probably be like this anyway since im a little newer to how C# works, but im also just wanting to get this done. i've been working at different styles of player movements for absolute days and this is the one im closest to finally managing since it turned out my software was out of date because my PC is due a fix.
I'm not too unfocused to comprehend instructions, im just a bit cautious in case i ruin it more since in the past that's how it's been - i'm so close to managing this. I only wanted a bit of help/an explaination, sorry if that's an issue or anything, im not a total beginner but when i've been trying to fix 1 thing for hours i kind of have to resort to help at some point
okay well have you bothered adding the line i suggested so we can see what is going on?
im working on it, on top of helping a friend with something
debug is a new concept to me, i'm assuming the {name} field is where i'd put the "move" in the line i got an error on in right?
it's different to the other code im used to with debugging so i'm just making sure
you don't change anything at all, you just copy/paste it exactly as is
it uh... almost froze my computer, wow
gdi my memory just maxed out
hang on i gotta shut some things down and try that again
that is entirely unrelated to the Debug.Assert call
i know, my computer just has some memory maxing issues, as i'd mentioned it's due a fix up soon
i just have to restart. common daily issue i'm having as of late
okay im gonna have to restart my computer. whole taskbar is duplicating anything i do over and over. brb
On startup. will check again shortly
pasted on that line. Went into play mode to initiate where the error normally shows up. What's meant to happen with the debug?
it's supposed to print another error before the one that was already happening
That has not happened, just the error that was originally there
show the full stack trace for the error then and screenshot the *inspector for * the object that this component is attached to
i'll copy+repaste incase i accidentally added/removed anythig then give that a go
Okay, looking up how to find the full stack trace and it seems people have been having to manually enable it in more recent versions of Unity? Anything I find on it says that. I'm confused.
Im a little more versed in older versions of Unity but this is different than it used to be. I had to do this once before a few years back and it was easy.
How do i go about finding full stack traces for errors? (might help for the future too. im still learning)
just click the error message and look at the extended information for it in the console
i am clicking it. and right clicking it. nothing changes unless I double click it, where it just takes me to my code editor. it doesn't dropdown, for whatever reason
all there is is what i screenshotted earlier
this is it. i have clicked it. in every place i can
it just repeats it below.
which doesnt change on clicking,
and just to be clear, you did save the code and let it recompile to test with the Debug.Assert call, right?
yes, thats when my computer froze. i re-pasted in case anything went wrong keyboard-wise, saved, and let it recompile since it didn;t get a chance.
and you put it on line 23 like i asked and not perhaps after the line that is throwing the exception?
just so you know I know how all this works, I know how coding software and game engines work. Unity and C# are just newer to me, and the way it debugs. I'm used to a visual novel maker, which uses the same save/manual reload/etc etc.
yes.
i did mention.
okay well i'm still waiting for you to show the inspector for the object with that component on it
was only trying to sort out the first issue.
this is exact to the tutorial, too.
i guarantee it is not because you missed a step
compare what the tutorial's Player Input component looks like with what yours looks like, you missed something
i am beginning to realise how non-specific unity errors are, eventually i'll learn what it could be... unity seems to like to keep things a mystery and make things difficult for learners. lol
but, im willing to learn
let me check. though i did check several times, i'll check again. sometimes it's that ooone check that does it
by component do you mean whats showing in script, or on the inspector?
in the inspector
yes, there's also a helpful message in your screenshot that should have made that fairly obvious
i'm aware, but i was not looking at his inspector before since he just briefly swung past it and didn't mention anything needed adding
sure but your inspector is the one with the helpful message telling you that nothing had been assigned
again, unity's errors are pretty vague i've noticed. it takes me to a line in a script when the issue's sat in the inspector on a different app.
i think my issue is that the software I'm used to is alot more specific with it's errors and what percisely is wrong, and where it is. The engine is entirely coding a game, without all of the assets and stuff like Unity. So that's probably why I'm a little more confused with this than what I'm used to
that is why I mentioned that it was something he hadn't mentioned. I hadn't bothered looking at my inspector because he just skimmed past it
issue is, he says nothing of what that item is, what it contains or where it's even stored...
like i said before, it's a bad tutorial.
i'll figure out from here im sure. thanks
well it's better than the other ones i've used - this is the only one left with a single error that i can fix
it's teaching terrible coding practice and apparently not explaining what it is doing, so if that is somehow the only one you've found that you can follow, then perhaps start smaller
i have tried, but again, this is the only one that's actually a) been one I'm almost able to complete and b) does what I want
I'm not making anything too serious out of this. im simply going to just learn from it - examine the working code, learn what makes it tick, what does what, etc
then i can just find other ways implementing the same kind of logic down the line as I learn more
it's how I did it with the other program anyway
if the tutorial isn't explaining any of what it is doing, then how do you expect to learn from it? also you're learning how to do things the wrong way anyway. so it's just overall a shit tutorial that you won't learn anything useful from
but if you want to continue with shit tutorials instead of learning how to do things the proper way, you do you. i won't be helping you further
well i am learning from it, im analysing it myself and taking bits from it
okay, but you don't really have to be rude about it. you didn't have to help me at all but you did. I'm grateful you did, by the way. Just got to figure out this UI input module and i should be all set
you're the one insisting on following a terrible tutorial that is teaching you incorrectly just because you can't comprehend other tutorials because you also refuse to start smaller like was suggested. there are beginner courses pinned in #๐ปโcode-beginner
start with those if you don't want to learn how to do things correctly
okay, jeez. i was only practicing and fiddling around and wanted a bit of help. i'll continue fiddling around with other code and such. im not refusing anything, i want to finish what i've spent hours on before moving onto something else. i don't really see why that's an issue - everybody's different. I'm just learning, analysing and experimenting in my own way and asking for help along the way. you really don't have to be rude about that.
thank you for the suggestions.
i'll probably just find some resources and then leave the server. I don't exactly feel welcome here with the way you've said some things in a patronising manner when all i needed was a bit of help and guidance. just seems to be a progammer server thing - if one does not know all, one is not worthy of knowledge. it's been every programming server i've been in, and i have had to learn two other languages by myself without outside help like these servers because everybody just seems annoyed that im asking for help. I will find ways to learn outside of this server. It doesn't feel like a productive environment to learn after looking through some chat history. It just feels like other toxic enviroments i've found myself in. Thanks for the help, but i'll find my own way out from now own. clearly this was not the right way to go about finding help.
we were all beginners once, but it just feels like a sin in the programming community to be a beginner or someone who doesn't know every corner of something, even a little bit. its not just here but Ren'py and some HTML servers ive been in too. and not just with me. I've sat back and watched it happen. In forums and everything. Maybe i'll just stick to myself from here on out
again, thanks for the help. farewell
if one does not know all, one is not worthy of knowledge
considering that is literally the opposite of what i'm saying, you're just bitching just to bitch at this point.
my entire point is that the resource you are currently using to learn from is teaching you incorrectly. the knowledge you gain from that will only hinder your development because it is wrong. I pointed you to resources that would actually be beneficial to you. but if you're just going to cry about being bullied because i'm pointing out that you refuse to actually learn how to do things correctly then i am absolutely blocking you. i don't help people who actively refuse to learn.
This is a stupid question, and I have no idea where to ask this, but...
When the inspector has the * to indicate unsaved changes, how do I save? I've just been selecting different things to force the inspector to switch to something else and open the dialogue to save or discard lol
Surely there's a keybind or something?
things like asmdefs (like what is in your screenshot) have an Apply button to apply changes. also not a code question
I know, but as I said, I could not find any channels that seemed remotely relevant. If there's a better place, I'd appreciate a pointer ๐
is it against the rules to offer to pay someone for help with coding in this disc
you should check #๐โcode-of-conduct
yes ๐ !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
how do i interact with drawn tiles on a tilemap in runtime? as in stretching existing tiles like a square tool
I don't think there are tools to modify placed tiles in the editor. If you really need that functionality, you'll need to write your own tool.
unfortunately ๐, i figured out a workaround with CellToWorld though, so at least i could get a list of the cell positions
Hello friends, I have a question about the Particle System in Games. What is the best way to create Particles for the game? Should I learn Unity Particle System or do you recommend a 3rd party program?
Anyone knows why it freaks out at angles near -90 even if I use the proper way? Here's my code:
IEnumerator AttackWithSword() {
canAttack = false;
Debug.Log("Started"); // Verified this only runs once
var t = 0f; // Raise the sword up slightly -- charge the attack
while ((t += Time.deltaTime) < chargeTime) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(-90, -110, t / chargeTime)); yield return null; }
t = 0f; // Drop the sword down in a slashing motion
while ((t += Time.deltaTime) < dischargeTime) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(-110, 15, t / dischargeTime)); yield return null; }
t = 0f; // Recharge and bring the sword back to its original position
while ((t += Time.deltaTime) < 0.5f) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(15, -90, t / 0.5f)); yield return null; }
canAttack = true;
}
Here's the video
I've verified that LerpAngle returns the correct angle, but the actual value in game is still janky. Same if I use ..rotation = Quaternion.Euler(..); or just use localEulerAngles
... and same if I just add 360 to all negative angles like so: Mathf.LerpAngle(360 - 90, 360 - 110, t / chargeTime)
See https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html. Unity does all rotations in Quaternions, so your code is flawed by assuming the angles it's reading back are consistent
I do know that, but is there something specific you're suggesting here?
don't do your rotations in world space; don't read from eulerAngles; store the initial local rotation and modify that using Quaternions (see Quaternion.AngleAxis)
I currently fixed by keeping the Y and Z components locked so it won't freak out, but I couldn't make it work with Quaternions since my animations are in EulerAngles and Quaternion.Euler didn't work
var (t, originalAngle) = (0f, sword.eulerAngles); // Raise the sword up slightly -- charge the attack
while ((t += Time.deltaTime) < chargeTime) { sword.eulerAngles = new(Mathf.LerpAngle(-90, -110, t / chargeTime), originalAngle.y, originalAngle.z); yield return null; }
t = 0f; // Drop the sword down in a slashing motion
while ((t += Time.deltaTime) < dischargeTime) { sword.eulerAngles = new(Mathf.LerpAngle(-110, 15, t / dischargeTime), originalAngle.y, originalAngle.z); yield return null; }
t = 0f; // Recharge and bring the sword back to its original position
while ((t += Time.deltaTime) < 0.5f) { sword.eulerAngles = new(Mathf.LerpAngle(15, -90, t / 0.5f), sword.eulerAngles.y, sword.eulerAngles.z); yield return null; }
that looks like the same code, just without using your extensions
the difference is that this one uses originalAngle instead of currentSwordAngle
but you're still reading from sword.eulerAngles every frame
no, that's inside a coroutine and originalAngle is initialized only at the beginning. Sorry for the weird formatting
the last while loop reads sword.eulerAngles.y and .z on each loop, so it has the potential to glitch out. And you're still doing the rotations in world space which is weird to me unless your player is absolutely locked into place with no chance of turning, moving, or getting hit
yeah that's fine I think since the object rotates.. and the reason it works is the angle.x never surpasses -90, so the quaternion can only be read one way
how would you suggest doing it with a quaternion multiplication and local space?
unless you know a lot more about how Unity has implemented its rotations than I do, that seems a weird and bad assumption to make. There are multiple ways to represent any euler rotation
would ideally like to have it work with abstract rotation/just follow the parent's rotation (the sword's rotation except the X axis), so totally interested in doing that
while ((t += Time.deltaTime) < chargeTime) {
LookAt((target.position - transform.position).WithY(0)); // What I would have liked to work. but doesn't cause of cached angle
sword.eulerAngles = new(Mathf.LerpAngle(-90, -110, t / chargeTime), originalAngle.y, originalAngle.z);
yield return null;
}
hm I guess I could use .forward = like always, since the sword's end always points forward ๐
.forward never failed me and this is the first time I need this weird thing.. just thought it'd be quicker to make the animation prototype via code lol little did I know
something along the lines of Quaternion.LookRotation(desiredSwordForward, -transform.right)
๐ฅณ thanks @mossy snow
LookAt((target.position - transform.position).WithY(0)); // Rotate towards the target
var desiredForward = Quaternion.Euler(Mathf.LerpAngle(0, -20, t / chargeTime), transform.eulerAngles.y, transform.eulerAngles.z) * Vector3.up;
sword.rotation = Quaternion.LookRotation(desiredForward, transform.right);
literally not a clue why this works and what would I have to do to change it.. just bruteforced it.. definitely need more coffee for this
you shot yourself in the foot again by reading from euler angles, and you're still doing world space rotation. Did you try rotating your test cylinder around +Y?
yeah it works on seemingly all angles ๐ Open to finding better ways though, I currently don't like the fact it takes 2 lines and still isn't really readable lol
does sword have any parent transform?
Sword's parent is the test enemy
I know my setup is doomed.. was really hoping for 5 min prototype before slapping in assets/anims but then math got the better of me
also, this in this context is the parent (TestEnemy)
Is it still not possible to configure two actions for a single-click (using the Press interaction) and a double-click (using the Multi-Tap interaction) on the same button without writing custom logic such as a coroutine? I'm using Unity Input System version 1.8.2, and have activated the flag for pre-empt actions. Independing of the settings, the single click is always notified.
do not cross post
Those interactions won't support it, no. You would need to write your own code or a custom interaction. The single click would need to wait some time before triggering to be sure it's not part of a double click
Btw the press interaction is not necessary most of the time
@mossy snow with some adjustments I made a horizontalAttack variant as well ๐
var t = 0f; // Tilt the sword backwards slightly -- charge the attack
do { AnimateSwordRotation(-50, 20, t / chargeTime); yield return null; } while ((t += Time.deltaTime) < chargeTime);
t = 0f; // Swing the sword towards the middle in a slashing motion
do { AnimateSwordRotation(20, -100, t / dischargeTime); yield return null; } while ((t += Time.deltaTime) < dischargeTime);
t = 0f; // Recharge and bring the sword back to its original position
do { AnimateSwordRotation(-100, -50, t / rechargeTime); yield return null; } while ((t += Time.deltaTime) < rechargeTime);
// Helper methods
Vector3 GetSwordAngle(float angleY) => Quaternion.Euler(0, angleY, 0) * transform.right * (rightHanded ? 1 : -1);
Quaternion GetSwordLookRotation(float angleY) => Quaternion.LookRotation(GetSwordAngle(angleY), transform.up);
void AnimateSwordRotation(float lerpMin, float lerpMax, float currentT) {
if (!rightHanded) { lerpMin *= -1; lerpMax *= -1; }
sword.rotation = GetSwordLookRotation(Mathf.LerpAngle(lerpMin, lerpMax, currentT));
}
not ideal since I don't have full control of the angles there but happy this works so far.
Context for anyone game-math-savvy: I'd like to animate the sword as shown here, but ideally in a way that'll allow me to work directly with local angles without relying on hacks like transform.up/right to acquire the rotations. Issue with code above is that it's a pain to include other axises in the animation. I don't really have to include them, but it'd be nice.
This spaghetti is unreadable, undebugable and unmaintainable, you are not doing yourself any favours whatsoever
could you not just use real animations for this?
id also just consider using gameobjects as starting/ending placements if you cant. Hard agree with steve, this code is bad for you
the transforms would store everything directly, and lets you visualize it in inspector.
I would consider creating a CustomYieldInstruction if you want your animations to be adjustable
Also, you can create an IEnumerator, if dealing with more your-like approach
private IEnumerator AnimateSwordRotation(float lerpMin, float lerpMax, float time)
{
float t = 0f;
yield return new WaitUntil(() =>
{
AnimateSwordRotation(lerpMin, lerpMax, t / time);
return (t += Time.deltaTime) > time;
});
}
yield return AnimateSwordRotation(-50, 20, chargeTime);
yield return AnimateSwordRotation(20, -100, dischargeTime);
yield return AnimateSwordRotation(-100, -50, rechargeTime);
very input
yeah initially it was supposed to be a quick & dirty placeholder until animations kick in, but at this point I don't see a reason to add animations anymore
regarding the code I kinda condensed it to post here without using up too much space, but it's kinda the code style I prefer anyway:
So, you prefer repeating yourself as much as possible?
thanks! I'm more interested in the math inside the helper methods though -- making a system that could straight up animate from/to any angle without needing new code
no that response was regarding bawsi's usage of animation files
e.g.: for vertical attacks, the helper methods were these:
very slightly different than the ones for the horizontal attacks, but require different code anyway
I'm talking about you repeating your code too many times, when it can be simplified to this
I'd like to turn this in a unified system that could straight up animate from/to any angle without needing new code
I hadn't responded to you yet when you asked that xD seconds later I said like your approach
-- or meant to say it lol.. sorry, I'm kinda sleep-deprived
i didnt say anything about the code style. the actual logic here being done is just bad.
Consider these 2 messages that you wrote
at this point I don't see a reason to add animations anymore
Issue with code above is that it's a pain to include other axises in the animation
Adding any new feature to this is gonna be a pain in the ass. I wouldnt even continue with this solution at all
Aka, the animator.
I don't think animator can be used when the player chooses how to wield the sword themselves
nothing being done here needs to be done this way. Id even first opt for using empty game objects as a start/end point for these "animations" before whatever this is. But it most defintitely can be done via animations or at least animation rigging
hmm when you put it like that ๐ค I'm pretty sure I have had bad exp with animator vs coroutines in game jams but that was many years ago.. I'll give the animator jam another go next jam
yeah pretty sure my issue was chaining logic & making modular animation sequences -- nevermind injecting some parts into the animation (like timed thrust in this case)
If the pivot is in the middle of the cube, then its bounds go from -0.5f to 0.5f instead of going from 0f to 1f.
[CustomEditor(typeof(GPNodeData))]
public class GPNodeDataDrawer : Editor
{
public override VisualElement CreateInspectorGUI()
{
VisualElement defaultInspector = new VisualElement();
InspectorElement.FillDefaultInspector(defaultInspector, serializedObject, this);
defaultInspector.Add(new Label("asd"));
return defaultInspector;
}
}
Does anyone know why i cant add extra label to defaultInspector in this block ?
Works for me. I would check namespaces to make sure your Label comes from UnityEngine.UIElements. Keep in mind that you need to use PropertyDrawer and CreatePropertyGUI instead of Editor and CreateInspectorGUI if you want your code to define how the object is drawn as property.
@hard estuary I just want to make this if node type is selector than i need to add 2 selection data fields more to that block what is the easiest way to do that add property drawer on NodeData class or add custom editor or something to SO script
if i was get it i can use custom editor on only mono and so files right ?
I've noticed Editor doesn't work if it's being written as property inside another Editor/Property. I assume they call something like new PropertyField when drawing those, which is drawing properties, not editors. I haven't checked what's inside though.
@hard estuary I would like to say that I am a little confused, how can I reach the goal I want to reach in the shortest way as I explained on the visual?
Try this:
[CustomPropertyDrawer(typeof(GPNodeData))]
public class GPNodeDataDrawer : PropertyDrawer
{
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
VisualElement defaultInspector = new VisualElement();
InspectorElement.FillDefaultInspector(defaultInspector, property.serializedObject, this);
defaultInspector.Add(new Label("asd"));
return defaultInspector;
}
}
In FillDefaultInspector last parameter want an editor instance that not accpect this i guess there is a comp err
I should've checked it before sending it. ๐ After making several attempts, don't think there is a way of drawing the default property drawer. base.CreatePropertyGUI returns null, other ways either miss something or draw everything recursively. But there is a chance I'm missing something.
I think I would just draw every property by hand. It's more work (especially if you have a lot of fields/properties), but at least it's a stable solution.
i guess i move forward with custom editor window for that and draw everything one by one with my ui elements and bind them to the serialized properties other methods wont work at least i cant
yea I agree with you ๐
I built my unity application and distributed it. People are able to play the game with windows. However, with windows 7 and 8 specifically, the following error is appearing for them: DllNotFoundException: FirebaseCppApp-12_0_0.
I appreciate any help on this as I tried so many things and searched the internet but no luck
Unity is not able to find this although in the game files it does exist
which coding backend did you build with
SO you don't know how you built your project
it's simple enough, Unity has several options to build your code with, which ones did you use
the default one, I tried other compressions as well
try
Project Settings->Player->Other Settings->Configuration
So you are using Mono and .Net Standard 2.1 which is not supported by Windows 7 or 8
.Net Framework, you can try Mono or IL2CPP
thanks
Just make sure your Firebase plugin supports .Net Framework, you may need to replace it with an OLDER version
hmm thats true thanks for that
fyi the framework version you are looking for, if required is 4.7.2
alright
how do you draw the circle made from physics2d.overlapcircle?
there is no circle option, best you've got is Debug.DrawSphere
yes it does and is against server rules
best, yes
there we go
what's the use of Vector2 direction in CircleCast?
the direction where the circle goes
there's already Vector2 origin, float radius, where is the direction supposed to go to?
origin is where the circle starts. radius is how big the circle is. direction is where the circle is shot towards. distance is how far it's shot
oh my god ๐คฆ, thanks for the explanation
why is W moving me backwards and s moving me forwards here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceshipControl : MonoBehaviour
{
public float moveSpeed = 20f;
public float rotationSpeed = 100f;
public float mouseSensitivity = 1f; // Sensitivity for mouse look
private float pitch = 0f; // Current pitch angle
private float yaw = 0f; // Current yaw angle
void Update()
{
// Handle movement forward and backward
float moveDirection = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * moveDirection * moveSpeed * Time.deltaTime);
// Handle rotation left and right (Yaw)
float rotationDirection = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up, rotationDirection * rotationSpeed * Time.deltaTime);
// Handle pitch up and down (using E and Q)
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(Vector3.right, -rotationSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(Vector3.right, rotationSpeed * Time.deltaTime);
}
// Adjust speed dynamically
if (Input.GetKey(KeyCode.W))
{
moveSpeed += 1f * Time.deltaTime; // Increase speed
}
if (Input.GetKey(KeyCode.S))
{
moveSpeed -= 1f * Time.deltaTime; // Decrease speed
}
}
}
Have you checked if the model is rotated in the same direction as the GameObject this script is attached to?
how do I rotate it without making it face a diferent direction?
That is not what they are saying
You have to make sure the model is rotated in the right direction before exporting it from blender or wherever
understood
The model is facing the right direction, if it's the same as the blue arrow here.
Moving it forward will move it in the same direction as blue (Y axis) arrow.
It's also worth noting, that the transform's Forward is a local variable.
How is your Vertical Input configured? If it includes W and S, then it will change both direction and speed. In such case, if your speed becomes a negative number, then the movement will be reversed (because negative moveDirection multiplied by negative moveSpeed will result in a positive value).
You're going to need to provide a LOT more information.
Do you mean DETECT input?
button.OnPointerClick(new UnityEngine.EventSystems.PointerEventData(EventSystem.current));
Or use OnSubmit instead.
Hmm, write a wrapper function, have the input call that function, or call it externally
Ah, a ui button
alr cool
yes
i have a render textue which im using to emulate button presses and i need to tell a button to act like it's pressed
(it's a render texture because the menu is rendered onto a 3d mesh
Having some trouble with async scene loading, heres my script:
but when I check my hierarchy, GameScene is loading forever
if I remove the allowSceneActivation=false, the scene switches to GameScene immediately, but with the allowSceneActivation=false, it doesnt actually preload, does anyone have any ideas what could be causing this?
For the record, when I press PlayGame (when the async.allowSceneActivation=true is uncommented), it finishes loading the scene
but not asynchronously^
Did you read the docs?
https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html
im having issues with simultaneous couroutines bypassing my cooldown system. For example, two different abilites share a cooldown, this works fine when one ability is pressed within a few ms of the other, but when I hold both keys, both abilities are used at the same time, bypassing the cooldown check. I believe this might have something to do with how couroutines function? not sure. This also occurs when I activate both abilities sequentially in an update loop. It seems the cooldown isn't being checked for the 2nd ability and is applying it second time
What does CheckCooldown do?
Debug the longestCooldown here before returning. Then reproduce the issue and see what value it has.
Are you trying to do Unreal GAS on Unity
yessir
the cooldown is being checked twice since its checked before input and after activation
how would i setup a script to disable a component of type i dont know?
Step through that method to see why longest duration remains 0.
Components don't have enabled property.
yea i kind of figured that one out XD
is there a way to do this without getting the type of the component
You need to know the specific type that implements the enabled property. Honestly, this kind of code is pretty bad imho. What are you trying to achieve?
i need to do this for my inventory system
i cant disable my items because i need to get references for them
so im opting to disable the components that make them an item instead
yeah i don't understand why it works completely fine otherwise
Why do you not have a reference to them?
Did you step through the code?
all items are childrens of the player
and all are disabled
until you equip them use them etc.
That doesn't explain why you don't have a reference to them..?
Just make a list on the player and put them on the list.
Or on an inventory component if you have one.
cant get their component if the item object is disabled
this is what im doing
So you do have a reference..?
Why not add the item to the list when you add it to the player/instantiate it. Or at editing time if you only add them in the editor.
i could do that but it would make problems in my system i havent figured out
i can sense it
Wat, why adding a new field would make problems?
it wouldnt be organized for one
if want to make a new item for my game with my plan i just create it and make it a child of the player
Wdym..? How is it organized now if you even don't have a reference to your items??
it will be once i figure that out ๐
yeah, its like the second ability doesn't see the first cooldown effect yet
therefore, it allows it through and applies another identical cooldown
If you want to avoid manually assigning them to the list, you can do that at awake/start.
oh i just saw this
see i didnt have to do all that thnks steve
Wdym by a "cooldown effect"?
And if it doesn't, that probably means that you don't yet apply cooldown at that point.
both abilities apply the same effect which holds a cooldown tag
i dont see how thats possible since the first ability should complete beforce the second one is activated
Then debug the timing of applying that tag and see why it doesn't happen before the second ability starts.
thats why I thought it was a couroutine issue but i could be completely wrong
It is most likely. I see that you're yielding in several places. If the cooldown is applied after the yield, it would happen on the next frame.
While the other ability is started on the same frame.
That's just an assumption though. You need to debug properly
i believe you're right, ill continue debugging but could yield new WaitForEndOfFrame solve the issue?
No, that would have the same problem, as the other ability would start right away, before the end of frame. Honestly, I don't see why you need to yield there in the first place.
where?
In TryActivate. That's the only code you shared that has yield return.
they are all couroutines since some abilities are done over time
im not sure how i could avoid using them
I don't think basing the whole system on coroutines is a good idea. But that yield return in itself is not the problem. The problem is where you apply the cooldown. You should apply it right away when the ability is passing the can activate check.
ill try it, whats an alternative to achieve the same effects though?
Finite state machine. An ability can be a class with Update method that you'd call and it would execute the over time logic if needed.
so using Time.time within loops etc
update loop
Mmm... Yes, but I'm not sure we're on the same page.
I'd have something like an AbilityManager plain class instance on the player controller. And I would call it's Update method from the player controller MonoBehaviour.Update. The AbilityManager would then in turn call the update of any active ability that it manages.
hm, thats completely different to how i have my whole system setup so not sure
i fixed the issue by doing this but now of course pre activate won't work since it wont wait for it to finish
I mean, if you really need to have it the way you had(which is a bad idea imho), you could just call SetCooldown() right after the can activate check and don't need any other changes.
why is it a bad idea exactly? just for the issue i was having or are there other issues that might come up down the line?
i still dont really see how your suggestion would achieve the same effect though
The issue that you were having is a symptom that it's going in a wrong direction. Coroutines have many limitations, like them being canceled as soon as the executing object is disabled. It can also be confusing how unity chains coroutines and in what order it executes what. If you update the abilities yourself, you have full control of that and don't need to delegate anything to unity and hope that it does it correctly.
What effect though? The only thing I've seen is a coroutine that activates the ability. I really don't see why you can't do the same with simple update logic.
being able to abstract whatever preactivation the ability may use and wait for it before activating the ability itself
Sure, super easy.
but yeah i do see that you could avoid coroutines
Just have a state machine in the ability with state like PreActivate, Updating, Ending or something and call the corresponding virtual methods.
No. Why does the state machine need to be in the TryActivate. It should be in Update or something. TryActivate should just make a check and set the ability state to Started/PreActivate or something. And probably set the cooldown as well.
It doesn't need to be. I already covered the update part in details a few messages ago.
i see
PlayerController.Update => AbilityController.Update => all active abilities update.
Anyways, I'm off to sleep. Good luck.
Main benefits of GAS is how it works with Unreal replication system, and prediction
If you are not doing multiplayer it could be much simpler
my system is not as complicated as GAS
its just to have modularity and ability to make stuff with the inspector
i do need a system like this though since my game is and APRG similar to path of exile etc
it would be a nightmare to calculate everything cleanly without it
Is there a way to programmatically decrease shadow quality in URP? I have baked shadows using bakery and use mixed for my character and enemies.
I want to add a graphics settings allowing to have both realtime and baked on, only baked (disable all realtime) and another option to disable all shadows (realtime and baked)
for some reason when i press W to launch off the planet it takes two taps of W to launch off the planet? idk how to fix https://pastebin.com/CnbqHumJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I'm using the Unity Splines package and I can't figure out how to set all the knots tangents to auto at runtime (through code)
The knots (and the spline) are being generated at runtime from transforms and I'd like to smooth out the result
Edit: Using spline.SetTangentMode(TangentMode.AutoSmooth) does an okay job but is limited, wondering if there's more tweaking possible
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/luxuwedobe.cs hello i am having this problem where my raycast isn't working basically it dose not render the hit is not getting counted i feel like the error is here
private bool OnSlope()
{
//first perfome a raycast to see if the player is hitting the slope
if(Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
{
float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
return angle < maxSlopeAngle && angle != 0;
}
//if it dosent hit anything
return false;
}
private Vector3 GetSlopeMoveDirection()
{
return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
} ```
hey i was using scriptable objects to define data for my guns
and now that im making an inventory system i realized it doesnt work for my situation as different guns using the same scriptable object would not work
what solution is there?
Create a different SO definition for each gun?
you mean making a new SO for each duplicate of the gun?
No, you create a unique SO for each unique kind of item/gun, and when you spawn that item, you use that SO definition to set it up.
yea i know that works great but what happens when you have two of the same gun as an item
they will share each others data
Well, you should have one item with a Quantity property set to 2
But if in your case you have unique ones, just count them. Have items store a reference to the SO they're using, so you can iterate and count.
how would this help?
Because you can show the item in your inventory with X2 on it? Otherwise, I don't understand what your actual issue is.
ok
I'm going off "I realized it doesn't work for my situation" where you don't actually describe said situation.
omg im so stupid
i dont know why im even trying to do this
i was using SO's to handle all gun information like damage ammo and etc
so when i had two guns of the same SO they would share the ammo
So real qucik queation. i have a SO that holds a list of a class and that class holds a list of other SOโs. Im trying to parse the second level soโs from a file. It works but in the inspector it says type missmatch and the data does not survive domain reload. I suppose I need to actually create the editor assets right?
is there a way to use physics2d to draw a quarter circle or something similar to simulate a sword slash. Right now im just using overlap circle to take a circle some distance infront of the player but the shape is off
if not, what way is generally used
overlap circle to get all objects in a circle around the area you'd like to check. then loop through them and use something like Vector3.Dot to determine how close they are to straight ahead of the object (or the direction of the slash) they are, if they are within some threshold apply the damage
great thanks
The answer was yes I need to actually create the scriptable object assets first
hey guys, long time unity dev, but bad at math and low level gfx
im trying to have a dynmaic cuboid
and i have the mesh working.
but i can seem to get the uvs right
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.
basicly i want it locked to ints for 1 unit mesurment, and have the same probuilder style texture on all sides
ive try a few things, even asked chatgpt for help. but i cant seem to get all the sides uv's proper
any help would be very appericated
Hello! I'm having an issue in my game... I have the player (blue) and a key which opens the door. The player must grab the key with the spacebar and keep it pressed to carry it. Everything seems correct but when I go to another scene the player is okay but the key wouldn't follow. What can I do?
๐ 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.
ah the bot is working now ๐
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!
you gave me a player controller?
Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public LayerMask floorLayerMask; // Set this to the layer your floor colliders are on
public float checkDistance = 1f; // Distance to check for the floor
private void Start()
{
}
private void Awake()
{
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
Vector3 newPosition = transform.position + direction * moveSpeed * Time.deltaTime;
if (direction.magnitude >= 0.1f && IsFloorBelow(newPosition))
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, targetAngle, 0);
Vector3 moveDirection = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
transform.position += moveDirection * moveSpeed * Time.deltaTime;
}
}
bool IsFloorBelow(Vector3 position)
{
Ray ray = new Ray(position + Vector3.up, Vector3.down);
return Physics.Raycast(ray, checkDistance, floorLayerMask);
}
}
yes
PickUp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pickable : MonoBehaviour
{
private Transform playerTransform;
public bool isYKey;
private void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 1f);
foreach (var hitCollider in hitColliders)
{
if (hitCollider.gameObject.CompareTag("Pickup"))
{
GameManager.instance.SetPickedObject(hitCollider.gameObject);
hitCollider.transform.SetParent(playerTransform);
hitCollider.transform.localPosition = Vector3.zero;
break;
}
}
}
else if (Input.GetKeyUp(KeyCode.Space))
{
if (GameManager.instance.GetPickedObject() != null)
{
GameObject pickedObject = GameManager.instance.GetPickedObject();
pickedObject.transform.SetParent(null);
pickedObject.transform.position = playerTransform.position + playerTransform.forward * 1.5f;
GameManager.instance.SetPickedObject(null);
}
}
}
private void OnTriggerEnter(Collider other)
{
if(isYKey && other.CompareTag("GateY"))
{
Destroy(other.gameObject);
}
}
}
so what does this have to do with a key not following player into another scene
also please use a bin site
for big code blocks
!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.
Change Scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Go : MonoBehaviour
{
public string sceneToLoad;
public Vector3 playerSpawnPositionInNewScene;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
GameManager.instance.SetPlayerSpawnPosition(playerSpawnPositionInNewScene);
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.LoadScene(sceneToLoad);
}
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
GameManager.instance.SpawnPlayer();
SceneManager.sceneLoaded -= OnSceneLoaded;
}
}
my bad!
well ofcourse the key wont follow because you dont even have a reference for the key
my suggestion is to spawn the key again on the player when in new scene
if you know they would have it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
when loading into a new scene you can check if a player had a key or object then spawn the key again on the player, or you can just spawn key on player when entering new scene if you know that the player already has a key
For scalability I would try to make a system that stores whatever the player is carrying at the moment and loads it on the next scene with the player. Then it can work with other items and makes opportunity for other level design choices in the future
hey there, i'm making a resolution dropdown for my game's settings and was wondering if theres a simple way to filter Screen.resolutions by aspect ratio? i could make a predetermined list and call indices from there, but it would be nice to grab available refresh rate from the player's machine
Do skyboxes work in 2D URP? I've read they don't yet there seems to be documentation on it and haven't had any luck
You just make your own list if you want something specific. Screen.resolutions is just a list of supported resolutions, the width, height, and refresh rate.
this is a coding channel
Write some code to filter it yourself.
i know unity default video player is AVfoundation
but somehow it seems that this built in features is encrypted and i cant access any codes regarding to this
which is normal tho, u cant access the engine source code anyway
the problem is, the video player is not working as expected in M2 silicon imac
is there an alternate way for me to change the code without using another video player?
it depends what kind of problems you're having but iirc you're not likely to be able to change any of the internal details of how it works so you might be better off looking for a 3rd-party asset
i need to change the "tolerance" of it to broken video
like at least i need to access the script file for the video player
Do someone know why the object dont destroy itself even if the value is the right value ?
{
if (GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Coincounter>().currentCoins == 1)
{
Destroy(gameObject);
}
}
how do you know the Destroy is being executed? Debug your code
That's because the value is not the right value
i mean i try and he is not but i dont knwo why
Well, it's not the problem with the Destroy method
Also, I don't know what you mean by "i try and he is not"
Hi, is it possible to create highlight effect on Game Object Elements (Vertices and Faces) in runtime without deconstruct the object into seperate vertices and faces of each one describe a complete entity of vertex or face?
like assigning individual face to unique color
strange because in the hiercahy in my Go the value is the same as what i want
i want to answer to steve to said i already debug it and nothing happen
If no error is thrown, either currentCoints does not equal to 1, or OnTriggerEnter2D is not called
Define "nothing happen"?
the object stay in the scene and in the game when current coins get a value of one
thanks do you maybe know why Ontrggerenter2d will not be called ?
When no collision happens
i'm stupid i don't know why y was using trigger the colison was to upgrade the current coins score but not the method to destroy it
so my problem is resolve thanks you all
Not entirely sure what effect you're going for, but this should all be possible through shaders
Is there an editor tool for monitoring UnityWebRequest? Something like browser dev tool network tag, where you can inspect each request, headers, payload, response, timing, etc.
Is it possible to check whether a type is serializable in Unity's Inspector? Type.IsSerializable returns True if System.SerializableAttribute is added, but despite returning true for decimal, its serialization is not supported by Unity
So, I have an Inspector for generic struct, and I want to check whether the type is serializable, because, otherwise, it throws an error in GetPropertyHeight
I found this, but it's not part of UnityEditor or UnityEngine, but a separate assembly I don't think you can reference in the project.
https://github.com/Unity-Technologies/UnityCsReference/blob/73c16d00a4c84d96ee9e097f5e289371a92133d3/Tools/Unity.SerializationLogic/UnitySerializationLogic.cs#L218
But you could copy the class, if you don't find any other way.
Got it, thanks a lot.
I've found out that SerializedProperty.FindPropertyRelative(string) returns null when the Type is not serializable. Not the cleanest solution, but it works and is pretty simple
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i have a path
a bezier path
i store the curve data into 2 List<Vector2>
List<Vector2> anchorPoints
List<Vector2> controlPoints
how do i make something move along :<
i have the formula for the bezier
but it works for 2 anchor and 2 control points!
i have many ๐ข
Can I see how you are getting that?
you can query a Bezier curve for any point along the curve
the yellow curve is done with Handles.DrawBezier()
altho the bezier formula looks something like this
Bezier(anchor1, anchor2, control1, control2, t)
and t is the thing you need, it's how far along the curve you are
I meant that is what you feed in, it will return the necessary point
how do i know if the thing is on 1, 2, 3 or 4
no, there is one curve, defined by 4 points
wat
how can I refer to a button in its script?
i have this code:
public void MenuNav(GameObject Activate){
gameObject.SetActive(false);
Activate.SetActive(true);
}
on a script im using to hold all the functions for my buttons on the menu, but when I place it on a button and click, it turns off the buttonlogic object, not the button
how can I make it turn off the button clicked?
ofc I could just make another script
The is the UI button component, right?
its one curve, and its defined by the four points
1+2+3 is just one number, defined by three numbers
yes
ill just make a different script though, it'll be faster
Movement along Bezier
Is this what you want?
private Button button;```
well of course I could do that, but that means creating a new variable whenever I want to make another menu screen
Is this just a data organization thing?
Trying to avoid boilerplates and such?
well i'd like to avoid adding an additional script component to every single button I have that disables itself
its cool, I just opted to do that instead, really not that bad
would you help me in the thread?
Make the buttons subscribe to methods in a menu script
plz help ๐ฅน
you have one bezier
comprised of four (actually looks like its five) points
five is a single number
composed of five ones
wat
why do you think this?
beziers (to my knowledge) look at the points and angles you've provided it, and creates a curve
because formula takes 4 points i got 15 :<
bezier shouldn't take a specific number of points, it should be able to use as many as it needs?
this is 1 bezier curve
correct
does it?
yes thats how beziers work
im not sure
but that bezier clearly has two points
(unless the green dots are also counted as points)
fair
2 anchors and 2 controls
yes
Ah, finally, the penny dropped
At this point, you should just use Unity's spline package
i know but i wanted to take the challenge
and its just overkill for what i need also
better to use spline then
forumists on their way to tell people that doing anything by yourself is a terrible idea:
a challenge is not what you want
well you can use spline if you want
probably more powerful
but if your are more comfortable manually making the curves, then do that
Challenging yourself is fine, as long as that's all it is. It isn't the approach if it's also being used as progress to complete something.