#archived-code-general
1 messages · Page 370 of 1
sorry
so whats stopping you with this?
the reference object in instantiating multiple times instead of only once
well just making it a corountine doesnt automatically make it wait for a set amount of seconds
i don't want it to wait actually, i just want that reference object to be instantiated only once when the player in inside the proximity
Currently, your logic is going to start a new coroutine for every frame that dist <= distance, which will most likely be far more than just once, this could also be throwing off your testing
exactly, but what could be the solution?
make it wait a few seconds after it calls
your script needs to remember if it triggered or not. So give it a memory
Yup, using a timer could be a good option, or a bool that the coroutine controls could be another option as well
What usually causes stack overflow in unity and how can i fix it?
Edit: I restarted the editor and my problem is gone : )
usually infinite recursion
I don't think any model is included by default. You're supposed to train your own. Unless you're talking about something else.
sorry i mean the training is really fast. When i try to make something like it (not for unity) its not even close to updating once per frame
im using keras
It uses pytorch under the hood, so should be possible outside of unity.
Hi everybody. Not sure if this is the correct channel for this, but I’m having an issue with switching quality level that causes Unity to crash. I have two scenes: a 3D scene and a 2D scene. The 3D scene is the main one. It seems if the game switches from the 3D scene to the 2D scene and I exit play mode, Unity crashes.
I attached screenshots of the errors.
I’ve got a ‘3D’ quality level and a ‘2D’ one.
Code:
private IEnumerator TransitionToCardScene()
{
SaveGameState();
QualitySettings.SetQualityLevel(cardSceneQualityIndex, false);
SceneManager.LoadScene("CardScene", LoadSceneMode.Single);
yield return null;
}
QualitySettings.SetQualityLevel(boardSceneQualityIndex, false);
SceneManager.LoadScene("BoardScene", LoadSceneMode.Single);
yield return null;
private void ReturnToBoardScene(bool answeredCorrectly)
{
StartCoroutine(ReturnToBoardSceneCoroutine(answeredCorrectly));
}
Any help would be much appreciated!
I’m using URP. Unity v2022.3
Did you try googling the error?
Yes, I couldn’t find any answers, though. I couldn’t find anything related to changing the quality level
I’ll keep trying to troubleshoot it, but if anyone has any idea on how to fix this, I’d really appreciate it
What URP version are you using?
And can you share the error details(stacktrace specifically)?
I created my project with the Universal 2D v2.1.2 preset. The default URP asset file is used for the 2D quality. For the 3D quality I use URP_DungeonsLite.asset supplied with the asset pack for the 3D scene I’m using: https://assetstore.unity.com/packages/3d/environments/dungeons/low-poly-dungeons-lite-177937 It uses the supplied URP_DungeonsLite_Renderer.asset.
I’m guessing maybe Unity isn’t handling switching between these two very well. However, it only happens if I switch from the 3D scene to the 2D scene and exist play mode. If I exit play mode in the 3D scene, it doesn’t cause the crash or errors.
I’m not sure how to copy the stacktrace because whenever this happens, Unity crashes, and I have to force-quit.
In Quality settings, ‘2D’ uses the default URP file, and ‘3D’ uses the Low Poly Dungeons Lite URP file.
I'm asking about the urp package version.
I’m not sure how to copy the stacktrace because whenever this happens, Unity crashes, and I have to force-quit.
Then how were you able to take a screenshot?
Regardless, you can get the stacktrace in the !logs
Dose anyone meet this problem? I post it just now, and need some solutions
https://discussions.unity.com/t/having-high-cpu-occupy-when-debugging-with-rider-after-finish-localizations/1520028
Thank you.
URP 14.0.11, URP Config 14.0.10. Not sure how to check for the 3D one I got from the asset store.
Here’s the full error with stacktrace attached.
There's no separation between 2d and 3d. 14.0.11 is the package version.
Thanks for the help, and I hope I’ll be able to fix this. It’s likely just an editor issue, but IDK. I’ll try posting it on the Unity forums perhaps
It’s some issue with changing the quality level.
At least I believe so
Looking at the stack trace, this is likely an issue unique to the editor only. And is probably related to the timing of changing the quality settings. Maybe try changing them after the scene is loaded and initialized.
Okay, I’ll give that a try. Thank you!
Is there a way to specify fields required to be set in the inspector? To make unity warn or even prevent starting the game until you set the value
You could maybe use OnValidate which will fire whenever the component changes, and I belive entering/exiting play mode - you could also use Awake or OnEnable to do checks in at runtime, otherwise youd probably need custom editor logic to do something like prevent play mode
Hi folk! I'm working on a project that is a kind of Vampire Survivors. I'm trying to optimize it to work with as much entities as possible - though I saw a strange performance leech in the profiler in Deep Profile mode.
public bool TargetInRange(out Vector2 direction, out float distance) {
direction = YKUtility.GetDirection(ownedObject.transform.position, objectToFollow.transform.position);
distance = Vector2.Distance(ownedObject.transform.position, objectToFollow.transform.position);
return distance < reachDistance;
}
have you got any idea about why this function is heavy? (400x entities, 22.7% total )
I think Unity is not caching transforms at all, and every time I call .transform it spends a lot of effort on it
should I just put the transform into a variable and let it consume RAM instead?
any information is appreciated and going to be helpful, thanks
you waste a lot of time fetching transform and position repeatedly. You waste more time on getting world position twice for each object, which is more expensive the deeper the transform hierarchy is. You waste a little time using distance instead of squared distance. You waste a bit of time casting Vector3 to Vector2 twice. This could be a good candidate to jobify btw, look at TransformAccessArray
that was useful, thanks! I'll give a look at c# jobs, looks like a good idea
to 300x entities, 10.2% total just by removing the unnecessary casting and duplication
using squareMagnitude instead of Distance, should give a considerable boost imho
I'll give it a shot, though it turns out the main problem was that my RareTick was getting triggered EACH tick..
I was wondering why the AI movement was so smooth.. lol
The final performance on build might also be much better on build compared to editor especially if IL2CPP is used
yeah definitely.. also deep profiling approximately halves the performance
Having an array, what is the best way to initialize it without an error thrown?
[SerializeField, HideInInspector] private Object[] _undoObjects;
// Awake
_undoObjects = new Object[]
{
gameObject,
numberText.gameObject,
difficultyText.gameObject
};
What kind of error are you getting?
NullReferenceException, since the array is null
Where is it thrown? Share the stack trace.
You're right. I'm ashamed, since that's texts that are null and they are on the same line as undoObjects. Thank you for your help
hey, could anyone help with accessing the new input system within a state machine? i want to assign a different function to an input action based on the player state and i'm not sure how to go about it
Try asking in #🖱️┃input-system. My first thought is creating action maps for those states and switch them when needed.
will do, thanks!
hi there
does anybody know why animator.SetFloat("Speed", value); wouldn't work (resulting in animator.GetFloat("Speed") = 0) even though "Speed" is guaranteed to be in the animator?
Perhaps something else is resetting it.
https://docs.unity3d.com/ScriptReference/Animator.SetFloat.html
because it does not have such signature or default value
corrected
Assuming you're actually using the correct signature. Otherwise there would be a compile error.
logging, just before
animator.SetFloat ( AnimatorParams.Speed, _rigidbody.velocity.magnitude );
Debug.Log ($"velocity: {_rigidbody.velocity}, magnitude: {_rigidbody.velocity.magnitude}, prop: {animator.GetFloat ( AnimatorParams.Speed )}" );
this shows prop: 0
Hi. If i have OnApplicationPause() on many script, is the execution order dictated by the settings i've set in the engine?
i cant seems to find an answer anywhere on the docs or over the web
Does it show velocity as not 0? And where do you assign the animator?
Should be. All of the messages are dictated by the execution order.
oh didnt see it myb
there is only one, and I do in the sample above
yes and in the same script, serialized variable
Okay. Can you confirm that the parameter doesn't change in the animator tab either?
also for applicationQuit?
ill give a try
Test it and see for yourself
ok i tried with OnApplicationQuit() and it didnt work
I'm trying to make something where light from an event travels outwards in a sphere and can be detected by various detectors; my idea is to give the light from the event a trigger sphere collider with an expanding radius, and then when it touches the detector's collider the detector does something. But I'm wondering if there's a better way to do it - there may be lots of detectors and I don't want them checking collisions with one another or similar
yes
Take a screenshot of the parameter in the animator
Get all the detectors in the range of your "light". Then filter out by the angle/dot product.
How can I make a vertical layout group put the elements above (bottom to top) instead of the usual top to bottom?
Don't crosspost.
found thiswhich i don't fully understand but works
https://stackoverflow.com/questions/55279138/how-change-expanding-direction-of-verticallayoutgroup-in-unity-without-rotating
Is there in unity / C# any common patter of storing safe/encrypted data localy?
Writing to a file. Wether it's binary or text. But no matter how you encrypt it, it's not gonna be entirely safe.
Sure, i just try to rewrite my storing data for game from XML to somehow secured like encryption JSON
The main goal is to prevent easy editing like text files or coppy from 1 device to another and run app with copied/ stealed data (they are not sensitive datas like Rodo or passwords etc... just some game saves)
I am writing the code for my game, and I am working with protobuf to transfer data. Should I keep trying to learn protobuf despite my issues with it, or go for easier JSON for now?
I will end up needing to use protobuf in the finished project, the amount of byte data and other user related information will give me no choice in my finished project.
Does anyone know how to fix my pitch? when it gets too high it sounds wrong. I have a audio clip for each note in the 4th octive. It could also just be my audioclips that sound wierd
public void PlayNoteClip(int octave, int note, int velocity)
{
if (note < 0 || note >= keys.Length)
{
Debug.LogWarning("Invalid note index: " + note);
return;
}
var obj = GameObject.Instantiate(keys[note].gameObject);
obj.transform.position = new Vector3(0, 0, 0);
var audio = obj.GetComponent<AudioSource>();
audio.volume = velocity / 127f;
audio.pitch = Mathf.Pow(2, (octave - 4));
audio.Play();
if (!obj.activeSelf) { return; }
GameObject.Destroy(obj, audio.clip.length);
}
Backing up and transferring save data is a pretty standard feature on platforms nowadays, so I would avoid trying to lock things down to a device. Simple edits can be prevented by using a binary format with the added benefit of most likely making things a bit more efficient across the board.
but isn't in reverse it unsafe to read binary code as it may be attacked from 3'rd party programs
I believe it comes more down to deserializer design (and how you use it) than the format.
Yeah i readed that decoding binary data can be executed as well so its not good idea at all to use it from local files
The vulnerability comes with BinaryFormatter, if you are not using that, you should be safe
There are other binary serializers, and if you want to roll your own file format, there's BinaryReader and BinaryWriter
Though you should be aware of the potential consequences of having code that deserializes any types, which most deserializers can be configured to do.
https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_TypeNameHandling.htm
https://github.com/MessagePack-CSharp/MessagePack-CSharp?tab=readme-ov-file#security
Is there any way to open a second window in an application?
I am trying to have the camera drag using the right mouse button, but it just refuses to budge when I DO click the right mouse button
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Sims3Camera : MonoBehaviour
{
public TMP_Text data;
public TMP_Text data2;
private Vector3 point;
private bool pandrag;
// Start is called before the first frame update
void Awake()
{
point = gameObject.transform.position;
}
// Update is called once per frame
void Update()
{
float xPos = Input.GetAxis("Mouse X");
float yPos = Input.GetAxis("Mouse Y");
//data.text = xPos.ToString() + yPos.ToString();
pandrag = Input.GetMouseButton(1);
if (pandrag)
{
point = new Vector3(point.x + xPos * Time.deltaTime, point.y, point.z + yPos * Time.deltaTime);
data.text = point.x.ToString();
data2.text = point.z.ToString();
}
else
{
//data.text = pandrag.ToString();
}
}
}
There's nothing there that would move anything
Hey, i am struggling with this particular Orientation problem, I want the character's Up and Forward axis to return to normal but also apply the additional rotation, this code seems to do this but the additionalRotation is applied in the wrong direction
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.
Is there a better way to combine those two FromToRotations and another quaternion?
And/or is there a standard practice for combining more than 2 Quaternions that I am missing?
then can you suggest something to me when you consider how the Gameobject in question is followed by a Cinemachine?
I haven't done anything like that with Cinemachine. You might want to ask in #🎥┃cinemachine about it
Essentially I want to have different displays appearing in different windows. I'm trying to set up a player side and game master view using multiple monitors. That could probably be done with networking but that would be way more complicated if I'm running it all on the same machine.
You can invoke platform specific APIs to create new windows. Rendering Unity elements on multiple windows might be complicated.
just use 2 cameras each set to a different display
Oh, right, Unity does have multi display support https://docs.unity3d.com/Manual/MultiDisplay.html
animator.SetFloat ( AnimatorParams.Speed, _rigidbody.velocity.magnitude );
Debug.Log (
$"velocity: {_rigidbody.velocity}, " +
$"magnitude: {_rigidbody.velocity.magnitude}, " +
$"prop: {animator.GetFloat ( AnimatorParams.Speed )}"
);
private static class AnimatorParams {
public static readonly int Speed = Animator.StringToHash ( "Speed" );
}
additionally
How come this code directly modifies the prefab, even if it seems properly instantiated?
[SerializeField] private DirectoryData rootDirectory;
[SerializeField] private GameObject buildMenuElementAsset;
private BuildMenuFolderController _rootElement;
public void Start() {
var folderGo = Instantiate(buildMenuElementAsset);
_rootElement = folderGo.GetComponent<BuildMenuFolderController>();
_rootElement.transform.SetParent(transform);
_rootElement.InitializeRootFolder();
BuildFolders();
//PopulateFolders();
}
(...)
public void InitializeRootFolder() {
Debug.Log("[Build Menu] Initializing Root Folder...");
_isAlwaysExpanded = true;
_expandDirection = ExpandDirection.RIGHT;
InitializeExpansion();
gameObject.name = "Directory - Root (Folder)";
_layoutGroup.transform.localPosition = Vector3.zero;
_layoutGroup.gameObject.name = "Directory - Root (Content)";
_layoutGroup.gameObject.SetActive(true);
}
instead of using a new Vector3 is there a more efficient way of altering one axis like this?
playerCam.transform.localPosition = new Vector3(0, 0.1f, 0);
create an extension method maybe
oh yeah i suppose
(this does not alter one axis btw, it reassigns a whole new vector)
Altering one axis would be:
Vector3 v = playerCam.transform.localPosition;
v.y = 0.1f;
playerCam.transform.localPosition = v;
alright cheers 👍
But to answer your question, no there is not a more efficient way since vector is a value type
But it’s pretty efficient to allocate new ones
And since it's a property
btw if you actually tried doing that you get infamous https://unity.huh.how/compiler-errors/cs1612
oh lol okay thanks
I think it might be because my prefab has a reference to itself (editor field) and it doesn't actually take the default prefab, it takes itself when instantiating
yeah, it was that
what a weird behavior
Is it possible to detect when Character Controller uses step offset to climb the surface?
not likely as that happens C++ side
😦
yeah, and its prob physxs implementation https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/CharacterControllers.html
🙁
What's the best way to extend the "hitbox" of a ui element?
depends on that shape ig.
maybe put a custom sprite above/under it with like 0 opacity
mb meant to reply to my own thing, turns out you can use negative raycast padding on any image, and most buttons usually have an image somewhere
negative means outwards for some reason
oh for square ig is easier?
I was wondering if the image component at 0 opacity would still work with alphaHitTestMinimumThreshold
since it states it grabs it from the actual sprite texture and not the renderer
(I guess ill just testit)
ohh, yeah if you have a more complex shape
and 0 opacity idk, i think i needed to use 1 opacity once
but i'm not sure if iirc
but yeah you can probably use alphahittest to fix that
lmk if u end up testing it
will do!
yeah even with Image alpha color to 0 opacity alphahittest still works, its getting the alpha values from original texture
so you can technically have invisible images any shape you want above it as hitbox to trigger whatever you want
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class BulletController : MonoBehaviour
{
[SerializeField] private float flyTime = 5f;
[SerializeField] private float flySpeed = 10f;
void Start()
{
var rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward * flySpeed;
Destroy(gameObject, flyTime);
}
}
Error:Skipped updating the transform of this Rigidbody because its components are infinite. Could you have applied infinite forces, acceleration or set huge velocity?
void ShootPlayer()
{
Instantiate(bulletPrefab);
}
Getting this error when bullet gets instantiated onto the scene
its telling you exactly whats wrong
Could you have applied infinite forces, acceleration or set huge velocity?
also check colliders when spwaned, make sure its not stuck somewhere or huge
Forgot to say that I'm not applying an infinite force, acceleration or huge velocity. I'm only doing this rb.velocity = transform.forward * flySpeed;
I see that
the computer says otherwise though, I tend to trust the results of the computer
have you tried debugging the values before passing to it ?
I'll try to. When it's an error like this I tend not to trust unity at all
var myVel = transform.forward * flySpeed;
rb.velocity = myVel
Debug.Log($"{this} myVel is {myVel} and current rb.vel is {rb.velocity} ")
there are checks in place for a reason, the calculator is 99% never wrong
when things dont work as expected is *usually * the users fault somewhere, not the computer
The only errors you can really treat like this are editor ones unrelated to your code. Unity is quite clear on telling you what's happening here.
Check the inspector for the prefab, it's possible you assigned it a large value somewhere there even
no that's not the case there are no large values assigned on my end
what you see here is not whats happening in the game so 🤷♂️
also where is the collider
it's a sphere collider
lol where not what
idk what you mean by where but it's on the bullet
Edit: I was being stupid I forgot to destroy the game object after it collided
I meant where is the component cause it wasnt on the gameobject inspector you showed
ik i didn't show the full game object
anyway I would suggest debug the runtime values
see whats actually happening in playmode
learning wise, whats the best way of actually getting something out of tutorial code? i thought of commenting it for what i knew but i dont know if thatll make anything stick
Hey quick question on if I am doing this right...
//add crafted item to inventory
InvItemData cloneItemData = GameObject.Instantiate(recipe.result);
Inventory.AddItem(cloneItemData);
Would something like this work with scriptable objects? I am instantiating a copy of the SO before saving it for later is this correctly how to do this? Will this mess with the original at all?
exists a channel for profiler theme?
its fine you can instance it and have data changes to the instance not effect the orginal
perfect thanks
i do it all over my code base, got a asset that represents defaults of something or inputs then i make in memory instances to work on
yeah lol i had the same thoughts
i dont know why my fixed update takes 120 ms :T
would just keep in mind the instances act like other unity object stuff so you do need to manually destroy them when done with them
gotcha
Can someone help me with figuring out how to pause a time line while using a dialogue box so it only continues after they hit the next button on the dialogue box please
use events
should be just a matter of adjusting Time.timeScale as needed and using events to handle anything else that needs to know about it
IpointerEventHandler, OnPointerClick works fine
just stop the application and continues when the player clicks the dialogue box
ima little unsure as to where i would put this code and exactly how, ill send my dialogue box scripts
or would i just make a whole new script for this?
make a new script
Okay so make a new script called (PauseTimeline)
i would need a reference to the timeline gameobject and the dialogur box object?
:T are you serious?
make a new script, call it whatever you want
implements IPointerEvents
im sorry im new to coding and very unsure on how to do this.. :/
dont worry
implements PointerEvents
when you show your dialogue box stop the timeline
in that script where you show your dialogue box stop the timeline
in this new script, you have to implements ipointervents
and restart or continue your timeline
you dont need any reference :T
Okay
When try to implement IpointerEvent just keeps red line, i know i need a function for it right?
yes, you need to implement the interface's members. you can also use the quick actions to do it automatically
when i do that theres like a bunch of functions it makes
Do I need all of these?
you sure you want IPointerEvent
assuming you want like IPointerClickHandler or something else
So just this then?
you have to check if you want what click is
Would I just use an IEnumarator with the waitforseconds?
using IPointerDownHandler, IPointerUpHandler you can check if you want specific clicks
right click, left click, middle click
why do you wanna do that?
nvm guess that wouldnt do cause it would just waitfor some seconds then continue,
Honestly I havent no clue what to put here.... ngl 😦
do you wanna wait seconds and wait for the player click?
or continue the game in the next seconds when the player makes click?
I want it to pause the time but still have players idle animation playing, but dont want the timeline to keep going unitil the dialogue box is closed
I thought it stayed on but it only stayed because the timeline time was over
I wanna wait seconds and wait for the player click through th edialogue then continue after dialogue is over
Hello i don't know if this is the right channel to post this in but im trying to setup Vivox and when im reading the docs they say that i need a Dedicated server to authorize the access token for the users?
becuse my game is going to use p2p
i'm not sure if you can run a couritine when the application is stopped
so it would have to go by counting the clicks?
Trying to get a NavMeshAgent to take knockback, but it won't leave the NavMesh area. How do I get the NavMeshAgent to stop sticking to it?
disable the navmesh agent while knocking back
it takes over your transform
👌
Consider just using navmesh to calculate its path and move it yourself, via rb or any other way, if you want to have unique ways of movement
Make sure you don't have spaces or invisible characters in the parameter name.
Loading issue inventory system
Hey everyone, I am currently trying to get the locationservice to work properly in unity 6 and on ios/editor/visionos. Somehow, everytime I start the locationservice like in the sample method here, its just crashing the app/unity editor
private async Awaitable VisionOSLocation()
{
locationService.Start();
Dispatcher.Enqueue(() => Debug.Log($"Status: " + locationService.status, Instance));
await Awaitable.MainThreadAsync();
await Task.Delay(10000);
Dispatcher.Enqueue(() => Debug.Log($"Status: " + locationService.status, Instance));
await Awaitable.MainThreadAsync();
}
The error happens right after start() firing Status.initializing on the next line
what sample method are you referring to and is the Dispatcher part of it? i don't recognize that and those MainThreadAsync are kind of weird
if you're expecting the function passed to Enqueue to be called from a different thread, you probably don't want to be passing in a unity object as the context for the log message
Nah, its just to run the awaitable on background but still wait for the mainthread to get unity callbacks in correct order. But I think from what I read in the latest forums, the new input system still does not support location services at all and I have to use both input systems to get the location service running... trying on the AVP right now to double check.
are you calling this method from the main thread? again, probably not causing a crash, but i think at least one of those MainThreadAsync calls is doing nothing
It is waiting for the mainthread but its being called from another backgroundthread
shouldn't LocationService.Start() be called from the main thread since it's a unity API?
Usually I get an error on xcode when it should, but I also tested the start thing to be sure, its not the issue
So starting from a background thread seems to kill it 100%. Starting it off the mainthread keeps the system running but its still stuck on initializing. If anyone had similar experiences with locationservices on mobile, let me know.
If I have a function bool HasFoo() then you'd expect that function to check if foo exists. Is there a convention for "look for foo and create it if it does not exist yet"?
When u say convention, do you just mean the name of the function? I'd probably go with like FindOrCreateFoo() or GetOrCreate maybe
Yes thats what I ment
bool CreateFooIfNotFound();
bool CreateFooIfAbsent():
bool CreateFooIfLacking();
bool CreateFooIfMissing();
bool CreateFooIfNotPresent();
You might take the following methods into a consideration, but since they are pretty long, I would consider simplifying it with Try at the beginning:
/// <summary>
/// Creates foo if not found
/// </summary>
/// <returns>
/// True if foo is found
/// </returns>
bool TryCreateFoo();
I tend to write out whole sentences sometimes trying to describe the function and was hoping that for this case some kind of convention exists. This is something that is needed regularly so I was hoping for some sort of standard. 😅 Probably overthinking this anyways lol.
Thank you both
chatGPT can help with following naming conventions ;p
This is generally a great and fast approach
Has anyone tried using Steam's auto cloud feature for saving game data?
I'm scratching my head at what I'm doing wrong causing it to not sync files.
T UpdateField<T>(string[] guid)
{
if(guid.Length > 0)
{
string path = AssetDatabase.GUIDToAssetPath(guid[0]);
return AssetDatabase.LoadAssetAtPath<T>(path);
}
else
{
return default(T);
}
}```
How do I make this work? The compiler throws an error for return `AssetDatabase.LoadAssetAtPath<T>(path)` because just writing T there is not allowed. typeof(T) does also not work.
You'll need to specify the type constraint probably
return AssetDatabase.LoadAssetAtPath<T>(path) as T;
Best to supply the compiler error
https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0314?f1url=%3FappId%3Droslyn%26k%3Dk(CS0314)
The type 'type1' cannot be used as type parameter 'name' in the generic type or method 'name'. There is no boxing conversion or type parameter conversion from 'type1' to 'type2'.
When a generic type uses a type parameter that is constrained, the new class must also satisfy those same constraints.
You haven't specified that T is a UnityEngine.Object
The method has to be modified as followed:
T UpdateField<T>(string[] guid) where T : UnityEngine.Object
Thats it, thanks!
Make sure to always check the generic argument when using the method
Not sure what you mean.
Make sure you always check the type of the generic argument, which, in your case, was UnityEngine.Object
You mean in the declaration of the method or before calling it in code?
I mean hovering the method or entering its script
I don't really know where to put this question, but what can lead to GPU Instances not working with light probes?
spent the whole day trying to get mlagents going but i always get an error when i type this mlagents-learn
some python errors ;-/
#1202574086115557446 for issues regarding ml agents
it's called a forum channel. and will actually be more beneficial to you as anyone browsing the channel will be able to more easily see your question and you won't get other people asking questions interrupting the flow of help
cheers..
What does that circle GIzmo at the bottom of the collider mean?
I think it might be the GameObject position/transform
Yes, you have the rect tool selected. Try pressing q w e and see how the gizmo changes
I have a very specific problem: I want my player rigidbody object to not get pushed by specific rigidbody objects, but be able to be pushed by specific others. At first I used an kinematic rigidbody but that does not do the trick, as I now want to introduce an object that can push the player. (If you answer please ping me) thanks for any help
if you want those objects to still collide but not affect each other but still be affected by other objects, then it is something that is kind of complicated. I know someone made an asset that can handle that for you, or you can ask them how they did it or even ask in #⚛️┃physics about how you could potentially set up interactions like that.
Here's that asset: https://discord.com/channels/489222168727519232/1247284826835517450
Thanks for the help! I now went with setting the mass of the I objects that should not push the player to 0 so they still push but with 0 force
Hey guys, i face a weird thing with addressables. I add reference of a texture in a scene. Both texture and scene are part of a remote bundle. So they shouldn't be inside of a build. But build size is increased by 1Mb.
Hi everyone. Does anyone know how to make the camera follow the player's movement direction? Like here in the video. Please don't say "use Cinemachine", I want to make my own fully controllable camera system. Thanks
(also for some reason the video doesn't load in Discord, so download it to watch)
You can make a fully controllable camera system with Cinemachine
You should have some idea how you want to achieve if it, if you're so against using the proper method of doing this.
Such as, getting a point that is behind/above the player's facing direction (using some simple vector math) and then slerping the position of the camera to it.
But yeah it's just some relatively straightforward vector arithmetic
I need help with my weapon system, using new input system with invoke method and when I keep my mouse button pressed it wont shoot continuously only once. I use Action and invoke them by subscribing from another script. It seems fine but doesn't work as intended.
The input system only tells you when something has been pressed, not held. You have to manage that yourself with a bool.
I'm pretty sure there is a way to do that without custom bools, the "GetKey" works on held for keyboard keys, so i'm sure there is something for the mouse too
If you don’t want it to use bools can have a coroutine that starts when you press it and stops when you release it lol
oh...any place where I can see how I can use it
Huh?
i knew
why reinvent the wheel
You're already using OOP
thats literally C#
yeah isnt components just classes
You can check this out if you want to improve your code
https://unity.com/blog/games/level-up-your-code-with-game-programming-patterns
damn thanks man , cuz now that i got a little bit code , stuff is getting messed up
do you have a specific issue you want to address?
It worked, thanks. Now the animation for the gun shot is played once, I have a separate script for animations. Ill have to fix that.
I am manually creating shapes (in this case hexes) and using shaders to color them inorder to create textures.
What are some things I can do to make the map seamless? I want to remove the shape(hex) outlines
If you want to remove the hex outlines why start with hexes in the first place?
It owuld be easier to make a square tiling texture
That is a good point, But I need the shape (could be square or hex or triangle) because I need to be sure of the specific biome/data of that specific location
Neat idea, tbh. I'd look into perlin noise and see if you can adapt it for hexes. It won't be easy, though.
thats not the problem, I have already done that
What, perlin noise?
the problem is removing the hex outline from the map
Your perlin noise generator will have to account for the coordinate of each tile, however - like, instead of a perlin noise function that's constrained to one hex, you'll have to broaden it so that any given pixel in the entire world belongs to the same contiguous noise function
ahh, I see
Like I said.. it's not gonna be easy but I think it should be possible since the noise method doesn't really care how big/small the surface is.. but your coefficients will have to be a lot smaller and you might run into issues with floats on the shader if your world is large
alternatively you could lean into it and make your hexes have borders - like PB said, if you're just intending to make a smooth texture, you may as well use square based grids since .. you're trying to obscure the borders anyway, and the math'll be a lot easier
Right now, im doing something similar to that, but I think the problem is that thesame constant value is used to seed the noise
yeah I dunno if I have the brain capacity to figure this out but I imagine you're going to need to have to calculate your noise value with a constant for "this tile" (id?) along with a constant for each of the adjacent tiles - such that the border along each of the 6 edges matches the inverted border of the adjacent hex
but I'm really shooting from the hip here.. that sounds hard
if you're looking for a smooth texture and using perlin noise, I'd probably just make a single square (or hex) and muck with the coefficients until you have a noise value that looks nice for the scale you're operating in
hm.. yeah.. it's an interesting problem tbh
apologize 😦
like I'm assuming you want something like this: https://www.reddit.com/r/proceduralgeneration/comments/majq3b/made_a_perlin_noise_based_hexagon_world/#lightbox
but with each individual hex to not be obviously a hex
indeed and not 3d 🙂
perlin noise for the hex type (at the world scale) and then perlin noise for the texture (at the hex scale)
lol, yea
at the texture scale, perlin noise is used,but its not seamless
I dont know why
yeah I think you're gonna need to dream up a solution for making a perlin noise function for the texture of an individual hex have the world location as part of the input so that the textures between hexes is seamless
it's a pretty hard problem (to do in shaders) tbh - i think even if you get it working the issue is going to be float instability because your textures are gonna need to be so small (for a float, relative to your world size) that as you start getting far away from the origin your textures are gonna look more and more pixelated as the floats start resolving/rounding to the same number
its getting better....
you did that just by feeding in the coordinate of the hex instead of the constant?
yea, the world pos. but.... let me just send small clip
sorry steven, let this one sldie please
It seems the random range is inverted...
Hm.. I think you're on the right track but unfortunately it's been a few years since I've done anything with perlin noise - like I said I don't think I have the brain capacity to solve this one
but I think basically you need each vertex of adjacent hexes to have the same value and function along the edge.. as far as how, that's above my pay grade 🙂
Your idea works, from this point i just have to tweak it among other things.
Thanks for the help!
I have a mesh that I'm adding a material to (at runtime) to outline it and render it through world geometry. The mesh is in a layer higher than world geometry, and I'm creating a local copy of the material and adding it to the mesh like so:
[SerializeField] protected SkinnedMeshRenderer OutlinedMesh;
[SerializeField] protected Material OutlineMaterial;
protected Material _localOutlineMaterial;
public void Initialize()
{
_localOutlineMaterial = new Material(OutlineMaterial);
List<Material> mats = OutlinedMesh.materials.ToList();
mats.Add(_localOutlineMaterial);
OutlinedMesh.materials = mats.ToArray();
}
It looks like it works, but when I set the color of this local material using the following, the part that "sees through" the world geometry uses the default color:
public void SetOutline(Color color)
{
_localOutlineMaterial.SetColor("_Outline_Color", color);
}
In the following shot, the default color is cyan, and the new color is red.
Why?
i cant see the gizmos like the camera sqare thing in the scence that tells you what you see in game please help
Did you try turning on gizmos?
how do i make something go forward in the direction of its rotation
like if i spawn it rotated by 45 degrees it moves in that direction rather than horizontally
for 2d
If you keep a local copy of the materials array and assign the entire array back using the materials property, does it differ? For examplecs _localMaterial = ... _local Materials = ...ToList(); ...Add(...); ...materials = ...ToArray();``````cs _localMaterial.SetColor(...); ...materials = ...ToArray();
I haven't tried that but I will.. I'm thinking it's something with meshes not updating materials and that I have to use MaterialPropertyBlock?
ie: the code snippet https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
nvm fixed
yeah that fixed it (setting property block)
I'm assuming that modifying a material copied to materials will not affect the copies.
transform.right or transform.up is the direction it is facing. Have your code move it in that direction.
yeah.. I don't know exactly how meshes determine that a material needs to be re-rendered, I would have assumed changing shader properties on a material would do so, but apparently not
(ignore the blue gun - but now setting the property to red using propertyblock instead of on the material directly works)
basically changing this to this:
public void SetOutline(Color color)
{
_localOutlineMaterial.SetColor("_Outline_Color", color);
}
public void SetOutline(Color color)
{
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
propertyBlock.SetColor("_Outline_Color", color);
OutlinedMesh.SetPropertyBlock(propertyBlock);
}
I don't know exactly why.. I'm still a little hazy on how materials work under the hood
So i have a namespace what unity cant find.
I added all the DLL's and the strange thing is visual studio says that he can find the namespace but why cant unity do this?
i added the packages with the visual studio add references
also put it in the plugins folder
I have a value in the range of 0 and 1. This value is my target. It jumps around in this range quickly, I would like to smooth out its motion, where we accelerate towards it the farther away we are, and slow down upon approach. Any built in functions to help with that?
Mathf.MoveTowards(...)
If you want it to slow down, you can use Mathf.Lerp(...)
Note that using lerp means it will never reach the target exactly, you will have to check that the value is approximately close enough.
Alternatively, you can get a tweening library (DoTween, PrimeTween, etc.) and use that to do it for you.
Oh would I have the delta scale based on the value between current and target?
MoveTowards will keep the speed consistent until it reaches the value
Right but I don't actually want that.
currentZoomRange = Mathf.Clamp01(currentZoomRange + delta);
var approachScaler = Mathf.Abs(currentZoomRange - currentSmoothedZoomRange);
currentSmoothedZoomRange = Mathf.MoveTowards(currentSmoothedZoomRange, currentZoomRange, Time.deltaTime * approachScaler);
Lerp will slow down as it gets closer, but honestly would just use the tweening library and use an EaseOut curve (or whichever curve makes sense for you)
found the issue, but dunno what causes it
some animation was overriding the paramter with a curve due to the name matching
renaming my parameter fixed it
When scripting custom inspectors, how can I get default Unity colors and styles?
Oh, thanks a lot! mb.
private void FixedUpdate()
{
_rigidbody.AddForce(-_rigidbody.velocity.y / Time.fixedDeltaTime * Vector3.up, ForceMode.Acceleration);
}
I just want to stop the cube from falling by applying the foce in the same direction reversed. But it still falls very slowly, how do I solve this?
you can just turn off gravity on the rb component
I simplified it as much as possible, in the real situation I can only apply forces and not manually change the gravity or velocity
why? this is just gonna be backwards. you shouldnt apply gravity, then counteract it, if you dont want it in the first place
also i dont think that alone would work, you'd need to consider the accumulated force as well. if you add force in the same fixed update, the velocity doesnt actually update til the next physics step.
that equation looks a bit off too. you shouldnt need to add DT in the eqation. the forcemode equation you choose can apply it already
I may be simulating grip anong a specific axis. In that scenario I want to apply a exact and equal force in the opposite direction. That's what I''m doing in the example but the cube still very slightly moves down
I'm converting the velocity to an equal acceleration in the oppisite direction. acceleration is velocity over time. At least that's what I think it correct now
I think it has to do with the fact that the force is only applyed in the next physics step. That's what it seems like when it slowly moves down
Here is when I activate the force when at y < 2
so I need to change the rigidbody acceleration during the same step I guess
or undo the last step
just wanted to make sure I'm not messing something up, this is the correct way to have the game run at 60 physics updates per second, right?
if there's a more precise way to have exactly 60 that would be preferable, since timer systems will be important to the game
Yes
The most precise would be to do this in code:
Time.fixedDeltaTime = 1f/60f;```
Hey in webgpu, what rendertexture formats can be written to in a compute shader? I find that neither rgbafloat or rgbahalf can be written to
you would want to set the velocity directly to have more precise control
You mean WebGL I assume? It depends on the hardware. You can use https://docs.unity3d.com/ScriptReference/SystemInfo.SupportsTextureFormat.html to find out
no, webgpu
but its not really about whether or not it supports it, I need to know if its read/writeable for a rendertexture
yes being built for webgpu with unity
and I have but theres not many resources on specifically webgpu for unity
and the webgpu without unity hasnt helped much either
I think you need unity 6 for webgpu
I see - webgpu support in Unity is in early access
that would be why resources are limited
Yeah
- Did you confirm that it works in the editor or a non we GPU build?
- Did you check the console for errors?
The only resource I could find really said that it only supported single component for rw
But that it would be fixed in 6000.0.2f1…
Can you even run webgpu in the editor?
The only way I could really debug was to inspect the web console in builds
Test it with different graphics API.
And it kept saying that argbfloat32 can’t be read/write
Vulcan, dx12, and dx11 work fine
What was the exact error?
I will have to get the exact error later here, walking home from class
I see. I imagine the final goal is for the webgpu to work the same way as the other graphics APIs. However, it's still not fully released, so I wouldn't be surprised that it doesn't work as intended yet.
Yeee
I wouldn’t be surprised either
But the whole not being able to read write to basically any render texture… how did they manage to get deferred working lol
I don't think you need to write to a render texture from a compute shader for deferred rendering to work.
Did you try running the samples that unity provides? Do they work correctly?
So I know it works
If I disable my program completely(it’s a custom pathtracing renderer), it works fine
Heyah! I'm new here and am currently taking an beginner-level university course on learning Unity and C#, I am having a bit of an issue with case sensitivity for a particular prompt for ZigZagMovement script:
What it keeps getting wonky about is the placement of the zigzagMovement as a class reference instead of a function. What do I do?
Wdym? Is there actually an error? What type is zigzagMovement?
Nm, I got it! zigZagmovement wasn't initially referenced in the X-axis script. It didn't have any function to reference.
That sentence doesn't make any sense, but if you got it solved, then 👍
There is nothing resembling a function in this line of code.
Sorry, didn't share the entire thing. Should've done that.
In various ways, but generally, the loading is done async, such that the game can update and render at it's normal frame rate.
What part of it? I didn't use any complex words.
Async means asynchronously and there are various ways to go about. The premise is that it executes in parallel with other code.
It doesn't necessarily have to be async await.
What I said has nothing to do with wether the game is multilayer or not.
As I said, they would usually generate the terrain asynchronously, such that the game can update normally while also generating the terrain.
It works for everyone. There's no reason for it not to work if implemented correctly.
I don't understand why you think multiplayer has anything to do with loading/generating the terrain asynchronously.
Has absolutely 0 relation.
Also, I'm not sure why you're talking about "ahead of time". This also has nothing to do with async.
You simply need to generate the terrain while allowing the app to update such that it can update and render the loading screen.
I can't give you exact steps, since it would depend heavily on your generation implementation.
I don't see how that contradicts what I said.
It fits in your step 4 and 5. Both of these steps would need to execute parallely.
Everything else is unrelated.
Ok, then what's the actual question? I thought you have a loading bar or something that is stuck when the terrain is generated?
I explained how.
But since you don't have a loading it doesn't really matter in your case.
You can just load it as you do it now.
There's no such thing as "let your computer use max CPU". The app doesn't have control over it. It always uses 100% of the CPU that the os gives it if it can.
No. There's no such threshold. The processor simply processes things at its pace.
You can't tell it to go faster or slower.
Unless you tune the hardware, which is unrelated here.
What kind of wait statements?
Even if you yield execution to the next frame, that doesn't change how fast CPU is processing things. It simple tells it "pause this work for now". The CPU would then try to do other work if it has any.
I don't think it should crash the server.
And if it does, then what is the cause? Did you actually debug it? Is it because the app is not responding to the os?
Well, you need to figure that out, because depending on the cause, there might be many different solutions.
Ok, then what is it?
What threshold is it? What kind of resources are you overusing?
What's max+?
But you have to. It is your responsibility as the developer and it's also the only way to address the issue.
I would understand why it happens first and then act accordingly.
A wild guess would be that you're running out of RAM or GPU memory.
So it has nothing to do with CPU.
Well, then what's right then?
The only other thing I can think about is that your server doesn't respond to the os, which I mentioned earlier.
How do you know that?
Investigate what allocates memory exceedingly and optimize that part using various techniques.
It depends on the cause. For example pooling. Or queuing the tasks so that they don't allocate the memory all at once. It depends.
Probably irrelevant, since it's on the server side. I forgot about it when I mentioned it earlier. But the answer is the same as with memory.
@spare dome setting velocity will allow for less control because I can't for instance break the rigidbody at a specific point only the whole body.
@lean sail The reason was because the gravity was applying in the following tick. So the velocity negating calculation was correct. The thing you see is the gravity applying one tick of force every frame.
The solution is to manually do the gravity force so you can add it to the negating calculation in the same frame.
private void FixedUpdate()
{
Vector3 forcesNextTick = Vector3.zero;
// Manually add gravity
Vector3 gravity = Vector3.down * 9.8f;
_rigidbody.AddForce(gravity, ForceMode.Acceleration);
// Convert current velocity Y to acceleration
forcesNextTick += _rigidbody.velocity.y / Time.fixedDeltaTime * Vector3.up;
// We need to add the gravity force this tick
// This is because the velocity above does not know about the newly added gravity force
if(_includeNextTickForces)
forcesNextTick += gravity;
_rigidbody.AddForce(-forcesNextTick,ForceMode.Acceleration);
}
Here it's simplified
private void FixedUpdate()
{
// Add gravity
_rigidbody.AddForce(Vector3.down * 9.8f, ForceMode.Acceleration);
// Get current acceleration
Vector3 currentAcceleration = _rigidbody.velocity.y / Time.fixedDeltaTime * Vector3.up;
// Cancel out all forces
_rigidbody.AddForce(-(_rigidbody.GetAccumulatedForce() + currentAcceleration), ForceMode.Acceleration);
}
Now the only problem I have is that it does not take in to account forces from other bodies :/
and it seems to be unsolved https://discussions.unity.com/t/how-to-find-the-force-being-applied-to-a-rigidbody/831268/12
is it possible to display this number as a binary representation?
when looking the object
you could just convert decimal to binary
long val = 753458;
string bin = Convert.ToString(val, 2);
Do you think this is doable @golden kindle
Ye I think so, but this depends on how advanced you make it and how advanced you are
Hi ! Is there a way to save changes made in Prefab Isolation Mode through script ? I found how to detect if I am in such a context, but the only method available on the PrefabStage that would make sense is ClearDirtiness(). Do I need to call AssetDatabase.SaveAssets() and then call ClearDirtiness ? SaveAssets on its own does not seem to do anything as the prefab is still marked as dirty with an asterisk (*) but it may not mean the changes are not saved ¯_(ツ)_/¯
Do you want to change things on prefabs through script too, or just autosave when you change something in editor prefab mode?
I make change through script that I want to save. Otherwise I would use the auto-save option.
Did you checkout the utility? https://docs.unity3d.com/ScriptReference/PrefabUtility.html
I did but was not sure it would make sense in Prefab Isolation. I saw ApplyPropertyOverride but assumed it would be for changes made on a prefab instance to be applied to the prefab.
Maybe you could show your code how you "open" your prefab through script and make the changes.
Actually it's not that I open a prefab. More context needed : I have attributes I can put on fields, properties or method to control the way they look in the inspector and extend the serialization to some stuff Unity normally does not handle. At some point, I had an issue that I fixed by dirtying the SerializedObject to force the refresh of the inspector. Outside Prefab Isolation, it's "fine" (not the best solution, but for now it works), but when I enter Prefab Isolation, the prefab is marked as dirty (obviously). Auto save would work, but my colleague wants to have it disable and ask if I can make the default dirtyness disappear.
So I'm checking if I am in a Prefab Isolation context to apply changes but do not know what to use to achieve my objective.
for (int index = 0; index < this.inspectorObject.TargetObjects.Length; index++)
{
if (this.inspectorObject.TargetObjects[index] is UnityEngine.Object unityObject)
{
UnityEditor.EditorUtility.SetDirty(unityObject);
}
}
UnityEditor.SceneManagement.PrefabStage prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
// code underneath is probably wrong
UnityEditor.AssetDatabase.SaveAssets();
prefabStage.ClearDirtiness();
}
Does not sound like the best approach, as you are targeting to different ways of modifying them. Maybe you guys should decide, if you want to use isolation mode or not? If not, you can just override as you do. But it also sounds quite counterintuitive to change prefabs that much without creating a variant anyways. Just trying to understand, why you would do so through script
Does autosave actually work ir hitting apply or is it still marked * when doing so with your custom serialisation?
Autosave works.
And I agree it's more complicated than it should. The first purpose is to update data that are not manageable with SerializedObject in the first place. The code I shared above is just to "re-sync" everything at some key point (for example: code executed to fecth data by the object that should be replicated in the inspector).
Are you sure you are getting this data and everything in correct order? Just wondering, if you are trying to save the prefab while its probably still fetching data, deserializing itself and therefore triggering new changes after you applied your cleardirtiness etc
This code is called once the data is fetched, bound to the elements and displayed
But heh, there is still room for improvement
Just for testing, did you just change a string or something simple and tried that again?
Change string, save the prefab and clear dirtiness, just to get all that custom jazz around out of testing and see, if you can save the preafb with simple changes
What I also found was something using
PrefabUtility.SaveAsPrefabAsset(yourInstance, yourPrefabPath);
as you got the prefabstage there, you could just get the instance from it and save it back to the path of your raw prefab
What I am also wondering. Are your changes saved even if its still marked * ?
As mentioned earlier, I mark the object as dirty to force a refresh of the inspector. there's not necessarily changes to observe. so just by opening a prefab in isolation make the * appears (since the forced refresh happens once). SaveAssets on its own seems not to affect the dirtyness, hence my question if it is the right method.
I.. I encountered this problem and its not even from any of my scripts?
can someone help me ith this, it happened twice, none of my script interact with this overlay script whatsoever, only a few has enabling or disabling agents, or ResetPath
Probably a UI bug. Does it actually break anything in your project?
no, it just stops the game and gives out the error
so deos this mean i can just ignore it? as in when the game is built, it will not crash it whatsoever whenever an agent is active?
Yes, it's an editor only error. it's not gonna happen in a build.
thank you
PostLateUpdate.PlayerUpdateCanvases take up to 15% CPU usage. Is there a way to reduce it? As I understand from the profiler data, my healthbars are problematic. Each healthbar has it's own canvas, and it seems like it is a bad idea. I have to make healthbar the child of the object so I don't have to fetch it's position frequently, which will result with performance problems as well. So what's the optimal solution?
Alright, my solution was making ALL the objects that aregoing to have health bars on them a child of the same single world canvas.
In this way, I didn't need to fetch the locations manually and I had them being rendered properly with minimal performance loss
You guys are great, thank you so much. With the recent recommendations you made on my other questions, I increased optimal enemy amount from 400 to 1500.
sorry for the visual mess, lol. Just stress testing
I'm trying to figure out a decent way to add scripts to my tiles for a mining game. I've painted a tilemap using rule tiles. Now I want to be able to click on a tile to remove it.
This would require me to attach a script to the tile but my brain is breaking. Can anyone point me in the right direction?
about script attaching - you can use scriptable objects.
https://youtu.be/XIqtZnqutGg
This tutorial does not directly link a tile instance to a script, I think it's not possible at all, but instead he attaches the tile type to a scriptable object with some data. When X tile gets clicked, he looks for a scriptable object that has the X tile in attached tiles list, then uses the found element to have the data.
In this video I to show you how you can use scriptable objects to store any kind of information in a tile. You don’t have to install any extras or make special tiles, you can use the standard tiles straight out of the box with Unity’s built in Tilemap. As an example I show you how to make those little bugs that check how fast they can crawl base...
if you want to attach a script to a specific tile and not tile type, then that's honestly out of my limits
for an instance, the tutorial guy in the video uses two tile types, "Grass" and "Stone". He doesn't attach scripts to tiles manually, but instead uses the tile types
the same guy has a tutorial that fits your needs better https://youtu.be/hPsB6MiJPQY
In this video I show you how to set your tilemap on fire, including how to change tiles via script.
Get the full project here (free) : https://github.com/ShackMan2000/TutorialTilemap
The part where the tiles are changed:
http://www.youtube.com/watch?v=hPsB6MiJPQY&t=4m40s
Get the fire prefab:
https://gofile.io/d/EDqHKj
How to make the f...
continuation of the first tutorial
Thank you for sharing these. I was looking into that first video before but in my mind I'm thinking a solution where the logic is attached to the tile itself works better.
Maybe that just isn't the best way after all though.
I see rule tiles have a default game object option but wasn't quite sure how to make use of this
i've been working on a "light gun" game. Aim around the screen and shoot (doesn't rotate character like a normal fps)
I created a way for the gun to follow the mouse.
I am using the PSX shader from the asset store, since the screen is just a raw image / "render texture" the actual "raycast" is completely off and not "straight"
I assume it has something to do with the res, but at the same time there could also be an issue with my tracking / gun pos.
I've added offsets, no matter what. when i put the mouse far left or far right of the screen, its out of wack.
private void PointWeaponAtMouse()
{
// Get the adjusted mouse position based on the provided offsets
Vector3 adjustedMousePosition = new Vector3(Input.mousePosition.x + xOffset, Input.mousePosition.y + yOffset, Input.mousePosition.z);
// Raycast from the camera through the adjusted mouse position to get the world point
Ray ray = playerCamera.ScreenPointToRay(adjustedMousePosition);
RaycastHit hit;
Vector3 targetPosition;
if (Physics.Raycast(ray, out hit, gunRange))
{
// If the ray hits an object, aim at the hit point
targetPosition = hit.point;
}
else
{
// If no object is hit, aim at the farthest point along the ray
targetPosition = ray.origin + (ray.direction * gunRange);
}
// Calculate direction from the weapon tip to the target point
Vector3 direction = targetPosition - weaponTip.position;
// Rotate the weapon body to look at the target point
weaponBody.rotation = Quaternion.LookRotation(direction);
}
This must be joke, does unity remote config supports arrays?
When I tried to get that JSON with array through cloud code then it worked in dashboard, but it doesnt work in unity itself
this is very confusing
what do you mean it didn't work?
I fixed it, it wrong version of that Json was saved in cloud save
I have some TMPro font .asset files which keep being updated/modified by unity and are making my git workflow a bit of a pain in the ass. The files have no modified data. Any tips/workarounds?
You have to add git ignore for TMP
Hm, I have a gitignore file in another project with TMP that doesn't have this issue.. what would be different about this project? Also, I'm not exactly sure what to filter here - i'm assuming .asset files are needed elsewhere in the project
I have a question. So I'm using this code to make my simple enemy ai walk around at random points within a circle;
{
Vector3 randomPoint = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, distance, NavMesh.AllAreas))
{
result = hit.position;
return true;
}
result = Vector3.zero;
return false;
}
void Patrol()
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
Vector3 point;
if (RandomPoint(transform.position, moveRange, out point))
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(point), turnSpeed * Time.deltaTime);
Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
agent.SetDestination(point);
}
}
}```
But I don't want it to move at random points within a circle, cause oftentimes it'll just keep going back and forth. Does anyone have any tips for how I could make the movement feel much more natural, like having the random point be within it's cone of vison rather than a circle around it?
If you say your another project doesn't have this same issue, can this issue be resolved by reloading the troublesome project's environment?
What, like a full library rebuild..?
I mean, I can do that but I'm just not sure why that would prove it - I'm not doing any sort of full rebuild in project B - every time I do something in the scene in B, the .asset files get touched by unity
my gitignore from project A doesn't contain anything specific to TMPro
https://pastebin.com/Dm1cErgn that's my template currently
Hold on, does your another project have the same issue?
project A & B both use that gitignore, have TMPro, but project B updates the .asset files for some reason
project B is unity6, project A is 2022.3
Project A doesn't, even though the modifications are the same?
I mean, I'm not modifying the fonts in either project so.. yes?
I don't know if I understand the question
I'll try to find a minimal reproduceable use case.. I think it's literally as simple as "drag a prefab into a scene that contains a GO with a TMPro component"
Do you have to save the scene for this issue to appear?
I think so, yeah.. but I have my unity setup to save the scene on play so I'm sorta saving it (implicitly) all the time
Yeah so.. lemme snap a vid. Fresh commit - just add a prefab to a scene (prefab contains a TMPro component and almost nothing else), save the scene.. asset files are mucked with
I would still try adding a git ignore for tmp if it's not added yet
It's
[Tt]extMesh [Pp]ro/
i mean, what's the string I'm searching for? I imagine I can't gitignore .asset files (unity internal files, probably?) - and there's nothing in the path of those modified files that contains anything related to tmpro
After user settings
I'd have to move that shit into a textmeshpro folder.. and to some extent, those files belong in git since the project wouldn't build without them
i'd rather find out what the root cause is and why this happens in one project but not another..
(I haven't found anything in TMPro preferences)
Yes, supposedly, the git ignore for tmp is triggered only when the tmp file in assets is changed
What I think is that you might have troubles with your .meta files
I would at least try Refreshing the asset database, reloading unity rebuilding the assembly
dynamic/static font assets
Yeah, that was it. Setting the imported fonts to static for all my fonts worked.
Need help with terrain and noise.
For some reason when I generate the noise I get this result. the texture is rendered for a grid of 2x2 of 513x513 pixel. but it sux 🙄
I mean, the problem is about the squares
Sorry /AFK
So, is it best practice to just never get null reference errors? Or where is the balance the two? I heard something in a video earlier along the lines of "in case the sound manager isn't working for some reason you wont get a null reference" to me, it seems like a sound manager should always be working no matter what
I'm here cuz I'm a beginner but,
adding a bit of noise to an image with a gradient or blur often helps to diminish the noticeability of image artifacts like that and banding.
You should basically never have a null reference error. Theres no best practice for doing something wrong
Oops fixed the wording
So I should in theory be able to write a whole script, with all references being null, and the script should be able to run (or just return) without throwing any errors?
Doesn't that cause a headache with debugging while developing because you won't know if something is missing?
No, this doesnt really make sense. Let's take a simple example, a movement script but the object to move was null. How would you expect the script to run? What would you expect it to move?
This shouldnt ever make it into the build. You see the error happen in the editor, you assign the reference and move on.
Can someone tell me whether this is a fine practice or whether there's a better way of achieving this effect?
I want to have grid movement (so ideally it's discrete) but want the sprite itself to smoothly follow the movement through dotween. I've separated the gameobject of the entity from the gameobject containing the sprite, and made this second object lerp to the original object in the update loop. This works fine, but I'm reading that in order to use something like dotween, you don't wanna call the dotween in the update loop (and I do get a warning for it in runtime when i do). So my guess was going to be to add an event to the original object along the lines of OnPositionChanged and then subscribe to that from the visual object and call the dotween there.
Is this a fine approach? I could also have the visual object be referenced in the main object script but I figured that if I ever want multiple things to react to the change, this would be a better way of doing it.
Alright fair enough. Thank you for the info! I guess I shouldn't be getting a bunch of null references when I stop play mode. Will fix those now. Thanks!
Hey, can anyone give me an idea of why my rotations might feel so unnatural? I've tried to use a Quadratic Ease in function to make the blend smoother but it still feels and looks horrible
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 find it kinda confusing what you're actually doing here. Dotween should be used more like coroutines, and not something you start logic for every frame.
I dont really know what this second object or separation of objects is for
I want the movement of the actual item to be instant and discrete, so only 1.0, 2.0 etc., but want the sprite to tween between the two positions for the course of 1 second for example. I wasn't sure how to separate those two movements so I put the sprite in another object and just made it follow the original object
Then yea you could use an event and just start the tween from there. Though I'd just use update tbh
Update with lerp?
Lerp if you want it to move a percent over time, MoveTowards if you want it to move a certain amount per second
Just to add to what bawsi said, what a "null reference exception" actually is is worth knowing. Little bit of programming history - you used to have to manually declare a block of memory to hold something like a game object, and you'd "reference" to it using a variable that held a pointer to that memory. That block of memory would have variables and so on. Say the size of your object is 100 bytes and the speed variable is located 16 bytes from the start of the block.. the executable would know that speed is defined at the address of the "pointer" plus 16 bytes.. or that it would need to write the new value to that location.
In other languages, if you didn't set your pointer properly, you'd try to set variables in memory where they shouldn't be - leading to your computer crashing usually.
Modern languages (mostly) have this "null reference" checking. So.. yeah, you're not supposed to do it. 🙂 Check to see if the value is null and if so, do the appropriate thing
As in use lerp on the sprite object to just transition over time? I was just gonna use dotween to learn it and since it seemed easier to specify my movement in seconds and such tbh
Also seemed to have decent APIs for things like animation curves
Indeed but I don't get why, if the resolution is correct:
{
NativeArray<float> noiseResult = new NativeArray<float>(resolution * resolution, Allocator.TempJob);
for (int y = 0; y < resolution; y++)
{
for (int x = 0; x < resolution; x++)
{
float sampleX = (x + seed) / (float)resolution * scale;
float sampleY = (y + seed) / (float)resolution * scale;
float noiseValue = Mathf.PerlinNoise(sampleX, sampleY);
noiseResult[y * resolution + x] = noiseValue;
}
}
return noiseResult;
}```
but the noise at the end sux, in quality and when I render it, looks like the pictures above 😦
Yes lerp would be used to move it overtime. Im not a big fan of dotween because of the memory allocations and I've really never felt like I've needed it
break the rigidbody at a specific point? was this about rigidbody joints? if not then explain
using the velocity would give you more control due to the fact that you can set it to whatever you would need
Thanks for that. It makes sense. I guess I just need to assume everything, even like a game manager could be null? Seems like a ton of extra code to add all the null checks but I most likely just need to learn how to do it properly
you probably want to learn the singleton pattern for your game manager so you aren't having to write a lot of boilerplate code through your app
Not everyone likes this pattern but I do 🙂 Lemme paste you some code
I have it set up as singleton, I was just using it as an example but yeah, thank you!
I'm inheriting from a Singleton class B)
If it's a singleton then you don't need to check if it's null
I wouldn't use that .. I'd probably use it as a DDOL and manually managed singleton
Theres no need to null check everything. As I said before, let the error happen in editor then assign the reference and move on.
public class GameManager : MonoBehaviour
{
private static GameManager instance;
private static GameManager Instance => instance == null ? FindFirstObjectByType<GameManager>() : instance;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
}
}
something like that
(in a DDOL in your loading scene)
Only if it persists/is don't do destroy on load, right? My singleton is not persistent, as it will only be used in a specific lobby (at least this was my theory when I made it, haven't gotten far enough to find out)
then your methods are like:
public static void StartNewGame() => Instance.StartNewGameInternal();
private void StartNewGameInternal() { ... do the stuff ...}
yeah, then you can manually load/destroy it for that scene
I just like the singleton approach because it makes interacting with the domain layer (the logic guts) pretty easy from anywhere
and then I pub/sub messages out to the UI to react to
but again, this isn't everyone's favorite approach and there's a lotta ways to skin this cat
Ohhh okay we're on the same page now. I don't actively have null errors. I fix them. I was just wondering if I needed to fix them and set up an extra layer of "security" with a null check
always, yes
Sometimes I do setup that extra null check if it's not something easy to debug. But stuff like accessing a singleton and somehow its null is usually the same execution order error.
If it's something thatd make me wonder how its null, I'll check and throw my own error with a more descriptive message
Well not throw, but LogError which I guess might throw by itself?
That's pretty much what I'm doing, very careful with where I use references to the game manager but there are a few "entity level" places where I reference it.
You just spotted a problem I didn't realize I had. I was thinking null checks were annoying because they hide the null reference - but that's because I'm not catching the exception I'm just using an if statement to return from functions or just skip stuff altogether. Thanks!
^ is the solution for this try-catch statements? or what's my next google search? if ya don't mind me asking
You shouldnt really need try catch here, depends what you're doing. Imo try catch is more for errors out of your control.
Like trying to read a file but the user deleted it. Not like "I forgot to assign this in inspector"
The solution really is just assigning the reference and running the game again. Theres nothing you should do code wise if you just didnt assign it
10-4. thanks!
Would also like to add a general solution for easier singleton adding. This does confine you to this base class, but you usually do managers etc. as a direct child of MonoBehaviour so this works pretty much every time for me
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : Component
{
public static T Instance;
public bool m_DontDestroyOnLoad = false;
protected virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
if(m_DontDestroyOnLoad)
DontDestroyOnLoad(this);
}
}
protected bool isTheOne()=>Instance == this;
}
you then do a
public class ShopController : Singleton<ShopController>
for example
you can add things like dontdestroyonload like i did, or handling more than 1 instance being detected (e.g. when scene-switching)
i have a function from an API that takes as an argument an Action<T, Channel>:
public void RegisterBroadcast<T>(Action<T, Channel> handler) where T : struct, IBroadcast
my question is can i pass an async UniTask into this instead somehow, like this:
private async UniTask OnMessageRecieved(RoomBroadcast msg, FishNet.Transporting.Channel channel)
currently it only works if its async void
Action requires the receiver method to return void, so your method is not compatible.
You could use an async lambda expression (or another async method) that returns void to wrap your incompatible method
RegisterBroadcast(async (msg, channel) => await OnMessageReceived(message, channel))
// or
RegisterBroadcast(Handler);
// +
private async void Handler(RoomBroadcast msg, Channel channel) => await OnMessageReceived(message, channel);
well i am trying to use UniTask since that seems to be what works for my webgl app, i'm not sure if another async lambda will work
hmmm ok
The two signatures are incompatible so you cannot do that without a "conversion" first
Currently have some code in fixed update that I want to still be able to run when timescale is 0. I tried to do something like this to replicate it since I heard that coroutines still worked at 0 timescale, but I'm not super familiar with them and it doesn't work. Is what I'm trying to do possible?
by doesnt work I mean it just prints once
How are you starting the coroutine?
On awake
use wait for seconds realtime btw if timescale is 0
Post the code, I suspect the issue is there
worked, thanks
If I want to move this mob all around the room (e.g. walking on the walls) and like faster and faster, does it make more sense to do it in Animation > Animation (and create an attack1 animation let's say); or should I proceed programmatically?
If programmatically, how do you handle the 6 body parts ? (since the mob would have to "break" in some sense as some parts would be on the vertical wall while others still on the floor)
It's a boss battle room like in Kirby so cam is locked when player is in combat zone
even setting the velocity directly does not solve the problem. During the same tick there will still be a force applied from ether gravity or other forces during the tick
hey guys, any idea what might cause the line Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue()); to return a different thing when used in two different scripts, in the same frame? I don't touch anything that would mess with the camera or the mouse
different in what way?
one time it's what you'd expect, the other it returns a vector3 with infinity in all positions
my only hint for what might be going wrong is that it's infinity when I query sceentoworldpoint in a script attached to the camera itself
where are you checking that?
in update, in a script attached to the camera
did you check which position value before it goes into the ScreenToWorld?
try assigning the Z value to it because if you're using prospective especially the Camera does affect it indeed
ah, I rubber ducky'ed my way to the solution, it was shooting errors so fast I didn't see, but I'm actually just stupid i incremented the value of the position of the camera instead of changing it, resulting in infinity after very little time
thanks!
hah nice!
Does anyone have any tutorial* recommendations for procedural world generation - biome generation? Something 2d but theres very few 2d tutorials in this topic and its just basic noise and not like a real biome generator. And 3d ones have conditions for like air or water, Whereas my terrain does not.
Something like terraria ?
Yeah that'd be a good example
kinda, it also has air/water/liquid calculations, mine doesnt
im trying to fill a map with biomes, But each attempt i keep just randomly getting random results. Like ocean is next to mountain next to plains next to ocean next to plains next to ocean, i think i messed it up bad and just deleted it xD
and now i need to refresh on something new here because im doing somethin wrong lol
How To Make A 2D Game Like Terraria / Minecraft in Unity! In this tutorial, I teach you how to make a 2D sandbox game like Minecraft or Terraria in Unity! It's easy to follow even for beginners as we go through how to generate terrain with Perlin Noise, animations, player movement, tiles and an inventory system!
Today we add biomes such as snow ...
Try this
İ just looked it up
Search "terraria biome generation" or "2d mc generation"
2D Game like Minecraft is a bit contradictory ngl
Yeah unfortunately thats just an else if video on the topic unfortunately. Its just checking if this works and then else if to the next
Oh let me search in Forma
What im trying to do is populate like a voronoi diagram
Which i admittedly iv tried but thats what i threw out xD dont think i did it right or its just not possible to use for what im attempting
Hey everyone, I'm working on a third-person controller in Unity and need some help with animation blending.
I've got the movement logic done, and my animations for walking forwards, backwards, left, and right are working perfectly. The problem comes in when I try to blend animations for diagonal movement (like walking left-forward or right-backward). I'm using a blend tree in Unity, and while the animation looks good, it plays very slowly during these diagonal movements. Another Problem which i encounter when trying to move diagonally in the backwards directions is that the left and right animations are swapped.
Has anyone else run into this issue or have any suggestions on how to fix it? Thanks in advance!
Are you using tile maps ?
If your problem is oceans next to mountains or rapid changes in terrain, what you should do is instead of making the biome decide the terrain, make the terrain smooth and pick the biome based on the local terrain shape—if that makes sense.
Tile maps? Like as in its a grid based system yes, chunk based, like unity terrains but has different triangle/vertice counts and saving etc.
Yes grid system.s
Did you try something like this ?
Unfortunately that too also leads to else if statements. If you do lets say make a map and each noise value = a chunk, You get stuck with consistent islands and consistent mountains of the same shape etc. I need to achieve like, Some more randomness, And im struggling to get that part, Because both deserts and plains will share the same height values, Forests too.
Like if i said 0.4 to 0.49 is plains, 0.5 to 0.59 deserts, 0.3 to 0.39 is forests, It will consistently be those regardless where you walk, Which does solve the inconsistency with biome grouping placement but makes the world super repetitive and predictable
Just zoom the peeling noise inside and out for different noises no ?
Whats that
Then you add some random maps like temperature humidity or weirdness for variety
Also there’s a way to expedite the process don’t check every biome using a list of if-else statements, if that’s what you’re thinking.
For a one parameter, let’s say you define your biomes off the terrain height, you can use a binary tree or smthing to determine the Biome in O(log n) for higher dimensions(more conditions) you get a similar performance using R-Trees
Okay thanks yall
Also Gweam you lead me down a new rabit hole, thank you
just found Ridge Noise along with this peeling noise topic
Yeah, Its a topic i just found googling zooming in (scale) on noise, Something something sampling still reading
Ah ok, I recommend simplex noise, perlin noise is slower, more artifacts and outdated but everyone still uses it cause it’s more famous 🤷
iv heard of it, not bothered with it, Wanna tell me about some advantages of it over perlin?
aside from performance
fair xD
guyzz I'm having a bit of trouble with my script. It’s supposed to stop a timer when the player hits the target zone,
but I got a bummer
Any ideas on what I might be missing?
!code, use a paste site
📃 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.
YAAAY FIXED!!!!
AMAZING 🥳
Also because perlin tiles easily
The impressive aspect is that the Burst engine is incredibly fast... It blows me away every time! 😂
Hi, I'm working on making a GOAP AI system for my game, but I'm a little stuck on how to handle types in C#.
For example, I have a class called EatAction<IEatable>. I have a bunch of food item classes that implement the interface IEatable (eg. Apple, Chicken etc..)
I want to be able to consider EatAction for each of these different food classes (EatAction<Apple>, EatAction<Chicken>) AND after that I also want to be able to set a specific instance of the food class as a target. So the IEatable part of EatAction<IEatable> can refer to the IEatable interface, classes of specific types that implement the interface, and also instances of these specific objects.
Tried to just make a list of EatActions with all the different food classes as a target, but I'm getting this error:
Stupid question, why the type is lowercase? 😅
Just temporary code to try and figure out how to handle this
I guess it should be eatableType?
Is there any toggle to make it so the cursor doesnt move when im doing things in viewport like moving around and turning while holding RMB?
Cursor.lockState = CursorLockMode.Locked; ?
And then Cursor.lockState = CursorLockMode.None; on RMB up
Is there any reason you're using generics here, instead of just passing the item to eat in the constructor?
If the generic is constrained only to IEatable I dont think you need it to be generic
Yeah I think I'm misusing generics here
I changed it to this:
So the variable target should be able to hold classes that implement IEatable, and also specific instances of those classes, I think?
Not sure what you mean hold classes and instances of the class. It's just a variable, which so happens to be of type IEatable. It will hold any instance that implements IEatable
that was attached I supposed ..
but it works
I don't want it to just hold instances though. I want it to also hold classes that implement IEatable without assigning a specific instance of that class.
That makes no sense
For example, I have classes "Apple" and "Meat" that implement IEatable. In the GOAP planner I want to consider EatAction with each of these classes, without having to supply specific instances of those classes, because there might not even be any instances in scene. Later, it would check if any instances of those types exist, and if so, set the target to one of those instances.
Like when the agent is first considering eating an apple, they need to consider doing EatAction to the abstract concept of an apple (ie. the class Apple), not a specific instance of an apple.
I'm not sure how your system is setup, but still this makes no sense. Are you familiar with c# fundamentals?
If you declare a variable of type IEatable, the only thing you're gonna store in there is an instance of something implementing IEatable. It sounds like you want to store the type of each thing implementing IEatable but this sounds wrong to need to do, unless it's purely for some editor functionality
Im also not sure what the goap planner is or looks like. wouldnt it make more sense to consider what foods are available first before looking at every eatable item, then decide what to eat? Rather than having it consider every type just for there not to be an instance
Yeah, I want to store the type of each class implementing IEatable.
Not for what I want to achieve. For example, there may be no instances of the class Meat in the world, but the agent knows that if they kill a chicken that will instantiate a Meat object. So they first need to consider eating Meat (as a class, not an instance), and then if the plan is selected the action will be applied to a specific instance of Meat.
One workaround I can think of is just to make an instance of each class (Apple, Meat) in the scene, but use them as a reference instead of a target. Then I could have two variables "targetType" and "targetInstance". targetType would hold the reference instance, and targetInstance would only get set when an actual instance of the class is found.
Well im still not entirely sure what youd use it for but Type exists. Though it's usually not the cleanest, to need to account for every deriving type, when implementing an interface is used to avoid needing the actual type in the first place. https://learn.microsoft.com/en-us/dotnet/api/system.type?view=net-8.0
That would still require two separate variables, right? One Type variable and one IEatable variable (to refer to the instance).
Maybe this approach would be easier/cleaner?
What are you going to do with the type?
Are you going to create an instance of it, find components of it, or what?
I'm still really unsure how you're going to be using it too, so I'm not sure. I was assuming youd have a list of types elsewhere
I would be checking the predefined variables of the class and comparing it to the predefined variables of other classes. For example, every instance of Apple is instantiated with a nutritionValue of 50, but every instance of Meat has a nutritionValue of 200.
How do you check the predefined value if you don't have an instance of it to check?
Now that I think about it, it's not possible to get values of Types, so having a placeholder instance of every item would probably make the most sense.
You would be able to do it with static abstract in newer C#, but unfortunately Unity is stuck on an old version of C#.
sounds like maybe it'd be possible to separate this so you don't have duplicates of eg the Meat data floating around? you could make Meat a scriptable object and have each instance in the world reference it
hey guys, does unity have coding?
wdym by "have coding"
it would be very odd the have the channel you are posting in if it didn't
right lmao
cause i have research and i have to develop an algorithm to make a 3d avatar based on user input (ther physical attributes)
I remember from yesterday and I'm still not sure of the correlation between algorithm and code in your case. You do not need code to develop an algorithm
what do you need to make an algorithm?
pen and paper
and what should i do next? can you guide me?
no, I am not your professor. Did you go and ask him about your research sources as discussed yesterday?
wdym yesterday?
you do not remember yesterday?
we have to get existing papers as our research sources
What are you studying? Surely the research is related to your major..?
yes
then that is where you start
So, you should know how to make algorithms..?
I already found algorithms from existing papers like parametric modeling, morphing algorithm and SMLP (i'm not actually sure if these are algorithms).
since there are like a 1000 different ways to do what we're describing, the algorithm will be my own, but i can stitch it together based on existing work and existing algorithms.
yes, it is part of my objective. i know how to code but literally have no experience when it comes to 3d animation. and i'm still learning
Then learn it. Unity manual and documentation is in free acceess. And you have the whole internet of information as well.
coding is irrelevant, an algorithm is not code. Code is what you use to implement an algorithm but you have to design the algorithm first
yes after the algorithm, i have to code it
yes but i need guidance cause i'm kinda losing hope... do you have an idea on how to do it?
I'm not even sure what you're trying to do. That's the part where you take pen and paper and write down the algorithm
This doesn't sound much like an algorithm to me. Just a simple app with ui and and some code.
but i think there has to be some way to make it unique right?
Wdym by unique?
i just don't have to copy and paste the existing algorithms, i have to design my own by stitching together based on existing work and existing algorithms
I think you need to go and talk to your professor and ask him for guidance, especially in terms of deliverables because it strikes me you have no concrete idea of what you are even supposed to be doing
you're right lol, this is what my group members have planned
do you know parametric modeling, morphing and smlp btw?
yes, of course I do, but don't expect that level of help from me, I gave up teaching many years ago
alright, i just wanna ask if i can apply it while using a 3d engine?
Absolutely, 3D is irrelevant in the context
what do you mean?
that's the point. the algorithm is the same it's just the implementation of the algorithm that is different
i mean why is 3d irrelevant in the context? i believe these methods are for creating 3d models?
because the only difference is you are implementing a 3D vector rather than a 2D one, and that is an implementation detail, nothing whatsoever to do with the underlying algorithm
oh okay i think i misunderstood, implementation detail and an algorithm is different?
of course, as I said here #archived-code-general message
oh okay so you mean the implementation detail is a code?
uhm i would appreciate if you keep being patient with me...
i really wanna understand what i wanna do
yes, the code is the implementation. the algorithm is the theory
of course they must, so what you should be researching is the underlying concepts of those techniques, not the implementations of them
alright, i'll try to find articles or research papers. i hope i'm doing it right
uhm can i dm btw? if that's alright
no, absolutely not
okay sure
i just don't wanna spill out the full details of my research while a lot of people can watch our message lol
but it's okay
You'd create a thread to avoid spamming the channel
right, would try that
Should we save the asset (prefab, SO) after changing the value of a serialized field through OnValidate?
I would like to set a sequential value to a field of a component initially
public abstract class PersistenceComponent : MonoBehaviour, IDataPersistence
{
[SerializeField, ReadOnly] private int _localId;
public int LocalId => _localId;
public abstract void LoadData(DataPersistenceObject dataObject);
public abstract void SaveData(DataPersistenceObject dataObject);
private void OnValidate()
{
if (_localId != 0) return;
var ids = GetComponentsInChildren<IDataPersistence>(includeInactive: true)
.Where(p => p != null)
.Select(p => p.LocalId)
.ToHashSet();
var id = 1;
while (true)
{
if (!ids.Contains(id))
{
_localId = id;
break;
}
id++;
}
}
}
Anyone?
I have a tilemap with blocks on it. I'm trying to instantiate a GameObject with an animator and sprite renderer at runtime when I click a block. It plays an animation over the block on click.
However, attaching the sprite renderer really messes with the gameobject position. Visually, the tile and mouse position are far apart, but position wise it is similar.
gahhh I figured it out. the sprite import setting here is what fixed it. Set the sprite import to local space (I'm guessing before it was using the canvas size i had set up in Aseprite?)
!ask
ive made a state machine for my game and theres a logic if player grounded you can jump once
im trying to change it to double jump
but im kinda having troble with it
my jump state https://pastebin.com/dTBemRd3
my machine state https://pastebin.com/5qP9dkDB
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
: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
just FYI the ask command is not to indicate you are asking a question, it is used to show someone else how to ask a question
what is the best way to have all the information for a capsule collider without one? 😅
Can I keep the component disabled and still ask for the radius and height? 🤔
you could
but if all you care about is Radius and Height could just make your own component for that
hello, i need some help with the trail renderer component, I want to add a trail effect to my character moving in a grid but trail bends/diagonally draws when my character moves too fast in an L shape. how do i ensure the trail follows the L instead of bending?
Is there any way to test my coding knowledge like a general test for c#? I want to know how much I do know, and do not.
for what purpose, like most would just start working on a project they want to get done
that will clearly show where you need to brush up on skills or not
I am working on my project, but I spoke recently with a full stack devoloper and he asked me how long I was coding for. I said for around six months, and I realized I had no way besides showing my code itself to show what level of knowledge I had in the subject.
so its hard to generalize, since the skills for working in different domains can change a lot
How do you convert a quaternion to a point on a unit sphere?
quaternion * Vector3.forward
hello, I am making a game about clicking on randomly generated targets and getting points however I have run into some issues with the code such as the target that I want to instantiate being null. These are my 2 pieces of code that I am using to generate random positions of the targets https://paste.ofcode.org/qvPFhawUk79GbRPjNz9MwC and the code I am using for the targets themselves https://paste.ofcode.org/37AvpHs47rB9HP4tmc5tgQU
I have a quaternion rotation, and I want to split it up into a pitch/yaw. (Angular rotation along X and Y axis). Any tips?
the target that I want to instantiate being null
then element 0 of yourtargetPrefabarray has nothing in it
That's literally what Euler angles are
Right I am trying to figure out how to make the code choose a random integer but I cannot just paste in the code to make a random range which is why I am confused on how I would be able to impliment a solution
but I cannot just paste in the code to make a random range
show what you tried? i cannot provide a fix for a problem you have not bothered showing or even describing until just now. but even still, if there is nothing actually in the array then you won't be able to get something from the array
Ok I think I'm overcomplicating this.
I have 2 normal vectors. I need normal vector A, to become normal Vector B, just through changes in rotation along the X and Y axis.
It's not possible for all vectors. For some (most?) cases you need to rotate along X, Y and Z, or rotate first X, then Y and again X (in local space)
in 3D space that is
Ok so more context. I have this sphere. I want to be able to hover over a region of this sphere with a mouse, and zoom on that point specifically. This is what I have currently.
void Update()
{
var delta = Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
var newScale = Mathf.Clamp(currentScale + delta, 1, 100);
var input = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z);
Ray ray = Camera.main.ScreenPointToRay(input);
if (Physics.Raycast(ray, out var hit))
{
normalIndicator.transform.position = hit.point;
normalIndicator.transform.up = hit.normal;
var angle = Vector3.Angle(Vector3.back, hit.normal);
var arcLength = Mathf.PI * currentScale * (angle / 180);
var scaleFactor = newScale / currentScale;
var arcOffset = (arcLength * scaleFactor) - arcLength;
float radians = arcOffset / newScale;
float degreeOffset = radians * (180 / Mathf.PI);
Vector3 axis = Vector3.Cross(hit.normal, Vector3.back);
transform.rotation = Quaternion.AngleAxis(degreeOffset, axis) * sphere.rotation;
}
sphere.localScale = Vector3.one * newScale;
sphere.position = Vector3.forward * newScale;
currentScale = newScale;
}
This is the code that's doing it.
The issue is that the sphere is also rotating along the Z while it zooms in. I don't want this.
I have no idea how to resolve that.
int randomNumber = Random.Range(0, 5); using this template to get a random range for my code
you also need to say what errors you get
but also you should be using the length of the array, not an arbitrary number like 5 as the max
Okay how would I set up the array though? I tried replacing targetPrefab for randomNumber and then dropping that into the code but that still just conflicts with the already existing code
I would change the length to be 3 as that is how many random targets I have currently in the game
can you be more specific than these vague phrases like "conflicts with the already existing code". you need to actually provide useful info that might help me figure out wtf you are doing wrong
Okay the exact message is that the game manager already has targetPrefab defined sorry
I have a WebGL breaks that compresses/decompresses json with gzip, and for some reason, if I build it using "Runtime Speed w LTO" instead of "Shorter Build Time" I get an error at the moment a gzip function is called in the game, thoughts?
I just can't wrap my head around what I would need to do to have random targets spawn in as everything is runs fine its just the extra targets
that sounds like you've either declared the variable more than once or you created a copy of the script somehow
okay I defined the targetpPrefab with the target class
huh?
private Target[] targetPrefab; is the exact line of code
so you have twotargetPrefab according to your error
yes and from here I do not know how to add on to the already existing definition of targetPrefab to make it an array
its already an array with []
you create a new one with size and assign values if its not serialized
okay gotcha
you probably want to expose it in the inspector as [SerializeField]
Yup got it
I set the array to be 3 in the inspector as I have 3 different targets that I want spawning and being treated the same as the targetPrefab
how can i send my code that isnt working
There still is the error with the instantiate saying that it clones the object original and returns the flone
provide the actual error message rather than a description of what you think it says
yes putting an entire array in an UnityEngine.Object makes no sense
you're putting a box where its a hole for a sphere
Touch touch = Input.GetTouch(0);
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
Debug.Log("yes");
return;
}
if (um.gameState == GameState.MainMenu)
{
Debug.Log("touch");
um.DraggedAtStart();
}
``` This is in Update. "Yes" get logged like 5 times but after that it logs "touch". The touch is over an ui element. No idea why does it first correctly detect it is over an ui (multiple times) but then doesn't
Okay what would be the correct code that should be placed instead?
just so you are aware, the error message is that bottom line that starts with CS0311, that first line under the signature is the summary comment on the method that describes what the method does
why not look at the code you shared before and compare what you had there (which was correct, but you just didn't have a random int chose)
that looks exactly like google earth
i see no issues with it imo
Controlling the rest of the Earth is kind of an absolute pain if it doesn't rotate around the poles.
well lucky you that earth does
not incorrect
My car is running away from another car. As it finds the shortest path in the navmesh while running away, it sticks to the side when it is going to turn the street. I want it to move exactly in the middle
how can I solve it ?
I wouldnt use navmesh for such use case.
Use splines
ok let me try that. thanks
makes things easier
also we have the same city asset 
ahahah, I think we are doing the same thing on this map
It looks very good.
The road splits in two. He'll have to go left or right at random. If I get in front of him, he'll have to run back. Can I do it all using splines? I tried coding it, but it seemed a bit like it was for npc animation.
yes its a bit tricky though
it gets really annoying but its possible
basically you need to know the specific index you want to go too
if you don't want to code all your navigation yourself, you should look into A*PathfindingProject Pro which gives you a lot of tools for doing this kind of thing. Note however that no astar based pathfinding solution will be able to truly handle vehicles on its own since the algorithm cannot understand an actor that needs steering, so you need an implementation where you can configure the graph in a way that this doesn't matter for your particular usecase. Navmesh is inherently not well suited for vehicles. with APP you get a bunch of path post-processing and steering options what can make vehicles behave quite nicely.
$140 seemed a bit expensive for such a small project. I think I will keep trying splines
its not a project specific buy, you can keep using it for all other projects too 😉
in any case, point graphs (which is what you need here) are a feature of the fee version, pro is mostly for performance and advanced navmesh usage.
Question,I've made a Main Menu for my game,made it as a separate scene and when im pressing play it's supposed to send me to the main game scene with ((these dont really matter)a text and a blurry backround) after 3 seconds to unfreeze the scene and let me play,but instead it crashes and stops the run.I've tried testing in Build & Run but it just closed the game.If someone can help me and needs the script,tell me and I'll send it.
I have completed the code process, but there is a problem. It goes exactly as I drew it, but the car teleports there because the knot is at part 0,0,0
Is it possible to start the knot0 in the same position where I started drawing?
script:
which drawing?
if you mean the one where the container lives on just copy and paste the position, they should be world post not local
Share the !code correctly:
📃 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.
Question, how can i code good graphics in unity 5 from scratch? I no longer want to copypaste someone else code, i want to do proper HLSL shennanigans With C# actually coded by me.
I no longer pírate asset store packs
thats embarassing that people do that
Why tho?
because its usually a developer putting work and you're stealing
and its not some corpo, its an actual indie dev most of the time
not something to be said proudly 🤷♂️
I Know, but doesnt éthics Apply on both sides?
I wouldnt sell or distribute the game With those assets Either, i Just was playing and testing them
Also im poor and underage so thats my point
meh its still not something you want to mentioned at all esp in a room full of devs.
Ooh
piracy talk is against this server rules just for future reference #📖┃code-of-conduct
Oh crud... i might been a little bit too honest
Yeah i realize
Well i already sent the message so hopefully nothing bad happens
anyway if you want to learn C# you learn c# , unrelated to HLSL
HLSL is used to talk to graphics/shaders directly. C# is versatile in different things
For a example, can i make a mirror in pure Csharp? Ive read that You have to code a shader
It depends the end goal. Unity can do that without even needing code, but generally a shader is needed. In c# you would probably not do such a thing
ShaderGraph exists also and requires no code, or you can add custom functions
Ohh let me search shadergraph to see if its What i think it is
Its quite neat, but its avaliable on newer unity versions, im using 5.3.x ||(I AM NOT USING A CRACKED VERSION THOUGH, I use a old version for looking into exporting to 7/8th gen video game consoles)||
Well, then you're limited by the technology of your time as they say.
also how would you even aquire the modded version of unity for that console
I want to do the graphics from scratch becuse of that
iirc you signed NDA and that gave you special version of unity
or that was just nintendo / sony
I Just downloaded the installer as a build module from archive.org and since the xbox 360 is out of support and we already had yknow... Microsoft XNA, i dont think theres anything wrong on using that
Anyways, you'd either need to learn to write shaders(and pretty archaic ones too), or fake it via a scene setup/render textures(if that's even supported)
Thats why i went here to seek help
Like documentation and resources
If theres even any
The older manual and docs should be available in public access.
Okay so I have added in a new array called randomIndex that has a random range of 0 - 2 as I have 3 different targets that I need to spawn in. that I then have then Instatiated with the same code that worked to spawn in 1 target before, I am still getting the object that I want to instate is full, this is my full code: https://paste.ofcode.org/37tQmQ3xn5vMdKep8B3LGmC
i assume you mean "null" rather than "full" and you're still not providing the actual error message, so this is really only speculation but i'm going to, once again, assume that your array doesn't actually have anything in it.
also you're still using a magic number for the max parameter of Random.Range instead of the length of the array
never mind I was just being stupid and forgot to put my prefabs into the actual unity inspector
thanks for putting up with my probably very frustrating explanations but I learned a lot
You're lost.
Is there a way to efficiently determine, when a mesh collider collides with any non-mesh collider (such as a box collider), what ContactPoints collided within the bounds of what triangles (so I would have some sort of enumerable of all the triangles that had the ContactPoints, and it would incorporate all of the collision points (So maybe something like a dictionary where the key is the triangle, and the value is a list of ContactPoints))
no i'm not, I figured i'd ask here .
You're lost. This is a Unity server
yes. I. Know. I make games too. but I figured that someone could help.
I'm not in one, Don't want any youtubers in my dm's
I have. Multiple times. I don't want to pay $12 a month when I already have spent $28,000 on my servers.
That doesnt change that this isnt the place to ask for that.
does anyone know how to make a working save file that can branch upon 27 different scenes in a unity fine that also is programed to make a file on the users computer that holds the save data? also that can encrypt the data so that people cannot change the save data?
Wdym by "branch upon 27 different scenes"? That sentence doesn't make any sense.

having, consisting of, or involving more than two branches
What branches? What does it even mean in the context of save files?
take a tree for example, a tree can have from 0-infinity amount of branches, in the end it is all connected to the stump. in this case, all of the saves can be connected throughout all of the scenes as well as the progress of which the player has made along the story of the game. The classrooms of my game are all put in different sections, kind of how "My Friendly Neighborhood" is set up.
in conclusion all of the progress would have to be saved throughout the whole game, location, enemies as well as the amount of coins the player has.
If you just need to save different data per scene, then you can have a serializable struct/class with a key and value fields, where a key would be the name/id of the scene and the key is the data you want to save. Then just have an array of those and save them as json or binary. If you really need to do encryption, then you're gonna do it somewhere in between these steps and writing to a file.
thank you for being a helpful individual on this server.
You'd get a proper answer right away if you weren't spiting out off topic bullshit.
So is there an effective way that I hadn't thought of yet, or is iteration the only choice?
I dont get how im still getting floating point errors when im snapping the value to 2 decimal places
You got your answer, be less annoying about it, thanks.
Show code and explain what errors you're getting?
is Collision.GetContacts what you want? im not really sure what youre trying to do otherwise
No. Basically, one way to see it as I have a cube (not forced to be a cube, really any collider) and a mesh collider. In the OnCollisionEnter I want to determine what triangles in the mesh collider collided with with what contact points from the collision. So lets say there are 100 contact points spread over 3 triangles approx equally, one possible thing to have would be a Dictionary where the key is a triangle, and there are 3 keys with values, and all the values would be something like a List of ContactPoints that have about 33 elements
HPS = Snapping.Snap(HPS, 0.01f)```
so its similar, but I need them split up based on which specific triangle of the mesh collider they contacted with (so which 3 vertices are they contained within from my understanding of how it works. I haven't worked with meshes much)
And frankly, I dont even think I even actually need the contact points themselves. Just knowing what triangles is the most important part
And the error is?
That occasionally the value goes to something weird with like 9 decimal places
Well one issue here is that 0.01f is not even a number that can be represented cleanly in binary
So shod i do 1/100
So even trying to pass that value into the snap function is problematic
To be exact
No that's the same thing
There's no such thing as exact here
It's like trying to write 1/3 in decimal
You get 0.33333... repeating
In binary 1/100 and 1/10 are such numbers
What you should do is use integers to represent these values in the first place
How
you could probably raycast against the collider using the collision contacts and get the triangle index https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html
long heliumAmount;