#archived-code-general
1 messages · Page 254 of 1
can anyone help me in this?
how do you load the scene
i know, I sent in #🖼️┃2d-tools but nobody responded yet
so i thought it might be okay to ask here caause i sent it earlier
then be patient and stop crossposting all over the place trying to get people to answer in there
I tried with:
SceneManager.LoadScene(0);
and with
var gameplaySceneIndex = 0;
AsyncOperation loadingOperation = SceneManager.LoadSceneAsync(gameplaySceneIndex);
yield return new WaitUntil(() => loadingOperation.isDone);
both works in editor but not in standalone tests.
have you checked the player !logs to see if there are any errors reported?
everything seems to be okay, no errors, also I saw it's loading the game scene in logs! So context of build scenes seems to be okay too. I guess there is different scene loading handling somehow?
Opening scene 'Assets/Scenes/GameplayScene/GameplayScene.unity'
LightingSettings: switching bake backend from 1 to 2.
Unloading 1 Unused Serialized files (Serialized files now loaded: 0)
Loaded scene 'Assets/Scenes/GameplayScene/GameplayScene.unity'
Deserialize: 4.469 ms
Integration: 187.602 ms
Integration of assets: 0.155 ms
Thread Wait Time: 0.012 ms
Total Operation Time: 192.238 ms
Unloading 1 unused Assets / (0.5 KB). Loaded Objects now: 7606.
Memory consumption went from 212.7 MB to 212.7 MB.
Total: 10.490500 ms (FindLiveObjects: 0.579000 ms CreateObjectMapping: 0.420200 ms MarkObjects: 9.464400 ms DeleteObjects: 0.025900 ms)
it's showing for 1s instead my gameplay scene 🙂 so it seems I am simply trying to do something wrong. I will go with editor play mode tests intsead.
Is it more appropriate and common to pass event args data as snapshot? I mean create a new instance and then pass it to listeners so that they see the event raiser state just in that moment
Hi. I did not find any channel for infra topics tangentially related to Unity. So apologies in advance if there is a more appropriate channel (or other discord server) for this question:
I've been designing/implementing a process for automated VFX and other performance tests using the Unity Test Framework and Performance Testing packages. I am able to run those tests from shell and obtain a results.xml file containing log messages and raw timing data from the performance tests. I could use a custom script to extract the data from that file and insert it into some other database or system to analyze it.
My question: Does anyone know of any good databases or systems designed for ingesting performance/profiler measurements like these, which would allow analysis and monitoring over time for performance improvements or regressions? I'm not sure which keywords to search for.
I stumbled on Prometheus, but that and its kin seems more oriented toward continuously monitoring webservices metrics rather than performance measurements related to one build artifact or batch job, so I'm unsure if it is relevant to my use case. I'm wondering if anyone here has any experience in this area and any recommendations.
private void AssignContentCard(GameObject parentObj, Material contentSidemat)
{
GameObject ContentSideCard = parentObj.transform.GetChild(0).gameObject;
//reset shader for urp mat, it may set in prefab when all game change to urp
ContentSideCard.GetComponent<MeshRenderer>().material.shader = contentSidemat.shader;
ContentSideCard.GetComponent<MeshRenderer>().material.mainTexture = GameManager.Instance.GetNoNumber_NumberTextureByNumberTexture(contentSidemat.mainTexture as Texture2D);//get no number card texture
if (contentSidemat.shader != Shader.Find("Universal Render Pipeline/Lit")) { return; }
ContentSideCard.GetComponent<MeshRenderer>().material.SetFloat("_AlphaClip", 1);
ContentSideCard.GetComponent<MeshRenderer>().material.SetFloat("_Cutoff", 0.1f);
}
private void AssignBackSideCard(GameObject parentObj, Material backSidemat)
{
GameObject BackSideCard = parentObj.transform.GetChild(1).gameObject;
//reset shader for urp mat, it may set in prefab when all game change to urp
BackSideCard.GetComponent<MeshRenderer>().material.shader = backSidemat.shader;
BackSideCard.GetComponent<MeshRenderer>().material.mainTexture = backSidemat.mainTexture as Texture2D;//get no number card texture
if (backSidemat.shader != Shader.Find("Universal Render Pipeline/Lit")) { return; }
BackSideCard.GetComponent<MeshRenderer>().material.SetFloat("_AlphaClip", 1);
BackSideCard.GetComponent<MeshRenderer>().material.SetFloat("_Cutoff", 0.1f);
}```
here are two functions that will reassign shader and reconfigure materials of certain gameobject
**it is already proven that the above functions work perfectly for ios/android/windows platform , however, only mac os build contains certain glitch (material is not updated properly)**
also, no preprocessor such as
#if UNITY_IOS``` stuff like these included
and on built app logs, the code also executed , i can tell from the debug log
even if im using mac os, it works well on editor, but glitched when built out as application
So I'm in the process of trying to make a physics engine what i want to do is detect a left and right input from the mouse and make it so that it stores that value Into a variable does anyone know how one would do that?
Left and right input of the mouse?
This isn't on unity its in visual studio
Show me settings of an material
I know
You want to get mouse pos, right?
on editor , before changing or after its changed by the code?
Both of them
Yus
hi which version of C# (and Unity) did this become allowed: List<Vector3> list = new(); //i.e. new() simplified constructor call
Use Cursor.Position
Here are some examples
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.cursor.position?view=windowsdesktop-8.0&redirectedfrom=MSDN#System_Windows_Forms_Cursor_Position
You need a vector 3 list?
no I can do it no problem - but now I can do new() instead of new List<Vector3>() I am asking when the c# support for that came
Whats the import of that?
Because that doesn't work straight up
List<Vector3> vector3List = new List<Vector3>();
Give me a sec
background: this project is on built-in renderer pipeline, however, we reconfigured a specific scene to use URP only, and its that scene gone wrong
the code above is actually changing the standard shader from BRP to lit shader to URP ,and then assign a texture as base map to it, it is not good, but works out in all other platforms
I guess
System.Windows.Forms
I guess you dont understand the new C# syntax available
2021+ because it requires c# 9
Change the shader before you build your project
that is it, thanks. so full or partial C#9 came in 2021 do you know?
Sorry, but i use old c#
theroratically , cant
this gameobject is to display cards, like the pic i sent above, and its a common display for all other scenes, so every scene will use this gameobject , despite some of them are URP, some of them are BRP
so if i pre-change the shader, all other scene will have problems lol
well I should have checked manual! I usually ignore new C# features until I realise I can save a load of typing or something!
also because VS keeps warning me of what I can do
but i think i will keep work on it tmr, thx 👍
Is unity safe because ive heard about the potential risks
Before i continue helping you, why exacly are you changing it anyway?
It might help me help you
if u dont use risky functions such as binary formatter, i think its pretty decent?
Depends what version/code you use
And for what
what risks?
I personaly dont know xd, but i dont like their tos so im stuck to old version
this project architecture, is built upon default renderer pipeline, but were planning to change all scene to URP , because we found out working in this pipeline is better, however, we had clients, we needs to deliver something out, so we cannot change it in one go, we can only change one of the scene in this stage, and will keep changing other scene
so all the settings and codes are default to renderer pipeline
im new to the team, but i think they use code to change it to URP because its fast?
like they dont bother to set or create another set of material/shdaer?
Just, change each individual material to URP
Yes, it will take time, but than you/yourTeam wont have problems
And it would be more preformant and smaller game size
cant, our team planning on a release in next 1-2 weeks to our boss
How much materials are there?
Change them to URP without any code
but were using the same materials on other scene, the same materials are used in both URP and BRP scenes
If you keep having problems with type of codes even tho you can manualy change materials, it would take you less time if you do it manualy
aight
I did not think you can mix render pipelines in a project yet - I thought that was on future list
i will talk to the team
Change all scenes to URP
but in fact we did it
theres one scene that is URP, but all other scene is built-in render
idk how they did it, buuuuuut
Tham change all to built in renederer
ok
Keep it simple, dont use 2 renderers
And those code for changing materials in runtime, dont do it, it could cause problems and delay the team even more
When i need to change the rendered, i change all materials manualy, thats why i keep all materials in seperate folder, so i can do ctrl+a and change them
If someone decided to add a URP scene and not convert the whole project, well it seems a bad idea in middle of it
I guess by break is over and i can continue on engine(combustion) physics
just had a short meeting with the director, they decided to change to single pipeline
either BRP or URP
but after our first release lol
Np
what makes it interesting is the team dont even have an exact answer of why changing a scene to URP in first place lol
Xd
Debug it.. put logs in various places to figure out what's wrong
Log inside the if (distance) and log out the values for current pos and target pos
and don't cross post, keep it in begginer
Currently I have a fighting game system where certain events can be fired at points in an attack using frame data, right now I do this in fixed update but that limits me to 50fps (as I don't want to break any physics by changing the fixeddeltatime). I'd like to move over to just doing it in regular update and manually setting the time for 1 frame so it's independent of the actual frame rate but I'm unsure how to handle frame skipping or lag.
If for whatever reason one frame had a high deltatime due to lag, it could cause all of an attacks events to trigger but at the same time, at the end of a move which is undesirable. Is the best way to fix this to somehow set a minimum frame rate so it slows down below a certain target? and if so should this be done with targetFrameRate and is there a way to set this as a lower bound (keep fps uncapped)
The other solution to this is just limit fps to 60 or whatever is desired, however this is a hack and slash game so I'd like to keep the frames uncapped where possible if it is
I want to steal this naming convention from Godot and use underscore in methods that are only meant to be called in ONE place. In this case by a pooling system. (In Godot they are used for engine methods) Do you guys think it's unnecessary? Bad idea? Good idea?
namespace Game.Core
{
public class PoolObject : MonoBehaviour
{
[AutoAssignFromChildren][SerializeField] private List<ISpawnCallbacksReciever> _spawnCallbacksRecievers;
public event System.Action OnSpawn;
public event System.Action OnDespawn;
public void Awake()
{
foreach (var item in _spawnCallbacksRecievers)
{
OnSpawn += item.OnSpawn;
OnDespawn += item.OnDespawn;
}
}
public void _OnDespawn()
{
OnDespawn?.Invoke();
}
public void _OnSpawn()
{
OnSpawn?.Invoke();
}
}
}
I would say...
What??
You want to have one script that you can call functions/programs from it?
Yeah, that's why I'm doing a sanity check on this. Initially I did it to avoid conflict between OnSpawn method and OnSpawn event, but now think that there is sth to it. GPT tells me it's a quite common practice..
Yes, I could actually lock it with a private interface, but kinda feel lazy to do it.
Hum
Reflection would be even more weird. But the point is that there are a lot of classes that are widely accessible that have methods that no one but one system is meant to be calling.
Pooling system needs to call poolObject.OnSpawn() and no one else
Ah, you are using a pool
in this case yes, but there are many other cases like this
Sadly, idk how is your pool made, so i cant really help you, ya know
But from just looking at it, the code looks fine to me
So I'd appreciate more opinions about this (the underscores) being weird or not 🙂
public void _OnDespawn()
{
OnDespawn?.Invoke();
}
public void _OnSpawn()
{
OnSpawn?.Invoke();
}
Thats nostly what i would write if i would need to call an function, so the thing you have should be gut
the underscores break convention
the underscores should only be used on fields
(and usually only backing fields)
but never on methods
I'm well aware that it breaks convention, so the question is: is the new established convention worth it? 🙂
Do what ever makes you feel comfortable and sod other peoples conventions, they're generally nonsense anyway
Basically if method has an underscore, don't touch it, it is called from one single location only.
The most important thing is, be consistent
I tend to think that way, but I might have some people working with this code base, and I don't want them to have panic attacks XD
true
I can tell you, having worked on hundreds of projects, the only ones which followed the same conventions were the ones where I was project lead and I decided what the conventions for the project would be
Ahh.. In any team I work in I'm the only one who cares, and same, if I'm the lead, that's the only way we don't have aZoo of-every-case PossibleAllOver THE_PROJECT _and everything else also in chaos
That sounds extremely unprofessional. Bear in mind conventions are an agreed lunacy, as long as everyone on the team is equally as mad it does not matter one iota what the actual convention is
You guys know how are these called? i searched code but didnt find anything. i just need to know what script calls them
https://i.imgur.com/HmL5eTk.png
Animation events
Not a script, your animation clips
how can I check if a stored ref of a gameobject is enabled ?
without using .enabled
gameobjects are not enabled they are active, so activeSelf or isActiveInHeirarchy
btw, this is something you could easily look up in the docs, that is why they exist
i forgot to delete my question, indeed it was very easy to find in docs.
sorry for the inconvenience
What way would you recommend for me to approach flag integration to my game? I have the player region names, so I though i could search for a flag pack that provides sprites of all the flags with letter codes as the sprite name. One thing is that it would require to constantly load the sprites from the files
A scriptable object? But to map 160+ flags would be a torture
Addressable or/and ScriptableObject that you can generate with a script.
yeah, one time script that generates that scriptable object i guess
easy solution, a zip file that contains all of your sprites and you just extract on demand, I use that exact system for a PokeDex with all of the Pokemon images in it and it works perfectly
you mean as to not have all the 160+ flags sitting in the project
You could also just load them when you need them and then cache the sprite. Or load them all at startup if on demand loading doesn't work for you
Addressable is able to handle on demand loading with minimal effort.
you still have them in the project just as 1 file instead of 160
You could even download image if necessary with addressable.
It's not a good idea to download. If leaderboard is populated with 10 different flags it could take some time
i mean, the images are 500 bytes each
all of them are like 200 kb, not a huge problem to have them in a separate folder extracted
If you are on mobile, you might need to download your resources beacuse you cannot publish a game with a size higher than 50m I believe on the Goolg Store ?
The file size limit is now 50MB for APKs that target Android 3.2 and lower (API level 13 or lower)
bro xd api 13 is like 10 years old
im targeting 29 +
published before 2021 august was 100, now 200
You are the one that choose. I'm simply giving you the information. Addressable can eventually solve those issue.
thanks, i'd try downloading from addressables if i come into an issue with the flag sizes, but i doubt it
i have a problem relating to triggers.
I have a ability shooter where i have a ray ability (I spawn in a collider for 3 seconds) and on trigger enter on that collider i check if the collision is with an enemy and then i trigger damage.
i move the rotation of the ray with
var lookDirection = (_castingPoint.position - target).normalized;
var lookRotation = Quaternion.LookRotation(lookDirection) * Quaternion.Euler(0, 90, 0);
transform.rotation = lookRotation;
and i move the enemy with a navMesh Agent
but for some reason it triggers trigger enter and then immediately trigger exit and then trigger enter and so on even though they are colliding all the time.
i tried making the rb of the enemy kinematic which didnt help.
dose anyone have any ideas on what is wrong / could be wrong?
(first on is the enemy, second one the ray)
AsyncOperationHandle<IList<IResourceLocation>> handle = Addressables.LoadResourceLocationsAsync("Flags");
await handle.Task;
IList<IResourceLocation> locations = handle.Result;
Debug.LogError(locations.Count);
``` why is this not working? I tried everything at this point, count is always zero
you're trying to read the result immediately after starting your async operation
you need to wait for the overation to finish before results will be available
isn't await handle.task handling that?
oh I didn't see that part
Is "Flags" a correct resource location? Shouldn't you be checking if the task was successful before reading the result?
i.e. https://docs.unity3d.com/Packages/com.unity.addressables@1.21/manual/AddressableAssetsAsyncOperationHandle.html
https://docs.unity3d.com/Packages/com.unity.addressables@1.21/api/UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle.Status.html#UnityEngine_ResourceManagement_AsyncOperations_AsyncOperationHandle_Status
isn't it looking for things labeled with "Flags"?
it has completed successfully
i don't understand why it has to be this complicated. All i want to do is load all the addressables in a group. Now i have to load the locations, then iterate through them and get the addressables seperately by the path
hmm this might be true
label them all as "Flags" if you want to load them with a key named "Flags"
Groups are uesd to organize your addressable assets
Addressable Groups only exist in the Unity Editor. The Addressables runtime code does not use a group concept. However, you can assign a label to the assets in a group if you want to find and load all the assets that were part of that group. See Loading Addressable assets for more information about selecting the assets to load using labels.
If all of these are in a folder, you can give the folder itself a label
#📦┃addressables has a channel btw, not that this needs to move but in the future
ah, sorry. Thanks
thanks @heady iris that worked. It turns out id rather struggle for an hour than read documentation for 5 minutes :/
Hi guys, what is the best way of dropping items from an Inventory? Right now i got an inventory system that stores ID's of items. I was thinking i could use those ID's to instantiate them from prefabs, but would that be a good way of doing it?
Yeah, that's a pretty common way of doing it
I usually use references to a ScriptableObject for the inventory item base data. The SO can have a reference to the prefab.
Oh hellyeah, for some reason i felt like there would be something terrifyingly bad about this approach but i guess not
thanks guys
hi, when I press W and D at the same time (or W and A) the player goes in double speed. How can I fix this? https://paste.ofcode.org/mv6CcuqaPCkjKhFc88CuB5
Normalize targetVelocity
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = Vector3.ClampMagnitude(targetVelocity, 1);```
thankyou
can anyone tell me why my enemies jitter when they move? im using simple rb.addforce method to move them ( movement is declared in the Update method but when i declared it in FixedUpdate it didnt change anything)
Make sure Seek is called in FixedUpdate
Enable interpolation
as i said, fixedupdate doesnt change anything in my case (for some reason) but i still changed seek to be called in fixedupdate and enabled interpolation. Sadly its still jittering
Yeah, I saw you said that. All physics should happen in Fixed though, so that's why I said it.
Now, is the PLAYER jittering, or could it be the camera?
Sometimes that's the issue
the player and camera is moving smoothly with rigidbody set to interpolate so its 100% enemy issue. I can send you link to my script if you want?
That's probably a good idea.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
there you go https://gdl.space/exowusicit.cs
I wonder if it has to do with that rotation line. Try commenting out line 34 in update (transform.right = )
will do
hi! i'm currently making a player movement script and it's working... BUT when rotated based on input, the new rotation is not the new forward, so it's relative to the global forward i presume, is there a way to set the last direction to new forward direction? here's the part of my code
void Update() {
HandleMovement();
}
private void HandleMovement() {
Vector2 inputVector = GetMovementVectorNormalized();
// sets direction based on vector input
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
float moveDistance = moveSpeed * Time.deltaTime;
float playerRadius = .6f;
float playerHeight = 2f;
//if nothing collides canMove = true
bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);
if (canMove) {
transform.position += moveDir * moveDistance;
}
isWalking = moveDir != Vector3.zero;
if (isWalking == true) {
playerAnimator.SetBool("isWalking", true);
Debug.Log("is running");
} else{
playerAnimator.SetBool("isWalking", false);
}
float rotateSpeed = 10f;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}
public Vector2 GetMovementVectorNormalized() {
Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>();
inputVector = inputVector.normalized;
return inputVector;
}
yeah it does, now its buttery smooth but why is it rotation fault? that doesnt make any sense to me
Rotate via the rigidbody, not the transform
The transform is fighting the rigidbody
whats the method for that?
depends on the rigidbody
setting rigidbody.rotation teleports the rb, transform, and all colliders to that orientation immediately, and does NOT respect collisions
rigidbody.MoveRotation tells a kinematic RB to move towards that target rotation during the next physics simulation, while respecting collisions
rigidbody.AddTorque allows you to add torque to rotate a dynamic RB in a certain direction
There is MoveRotation
https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html
And simply setting rotation
https://docs.unity3d.com/ScriptReference/Rigidbody-rotation.html
holy, i didnt know rigidbody.rotation existed
it’s really dangerous to use unless you are really teleporting
alright thank you @spring creek and @hard viper! that was really helpfull
you can clip into a wall, and it won’t stop you from doing it
there is no resistance. you’re just saying “I want you like this, now, and don’t ask questions.”
MoveRotation is like moving the object with infinite mass. It will go to that rotation, while plowing anything out of its way, and not being stopped.
well then how can I set up something simillar to my previous function but with rigidbody? I kinda don't know where to start
AddTorque just adds force, which applies if you have a rigidbody that is affected by and responds to forces from many thigns
depends on how you want something to move
i just want it to rotate in the direction its moving
if you have a gameobject with colliders, and it moves, you want to give it a rigidbody, or else unity’s physics system won’t acknowledge its motion
colliders in the scene won’t respect its motion during physics simulation
first you need to decide how you want it to move
im moving it with rigidbody.AddForce
do you want it to push things while never getting pushed back?
so it’s dynamic
that is tricky
nooo, i want my enemies to move and push things while i can push them as well
does the shape have rotational symmetry in the axis of rotation
eg capsule collider rotating along its long axis
i have circle collider
and the rotation is about the center of the circle
and there are no colliders attached to it (that are not circle colliders at the same center)?
if anyone knows how i could fix this it would be super appreciated!
you can set rigidbody.rotation without issues, as long as the rotation does not affect your collisions
but this sounds like the sprite should rotate, and not the rigidbody
eg sprite is on one gameobject that rotates, which is parented to the RB
i managed to do this
rb.MoveRotation(Quaternion.LookRotation(rotation));
rotation = target.transform.position - transform.position;
and it works very smoothly
if your rigidbody is dynamic, that is a bad idea
why
MoveRotation will override other shit you have going on
idk if it is different for 3D, as I specialize kn 2D
MoveRotation overrides velocity etc
at least I know that to be true for translation. not super sure about rotation
but it accelerates alright and everything
if you say velocity = (1,0), and you say MovePosition to a point 2 units up, then the next frame, you’re ass is going directly 2 units up
idk if MoveRotation has like a separate channel, since i try to avoid rotation in my game
i assume it has a separate channel that then overrides angular velocity, which then makes angular accelleration and torque not apply for that frame
oh, and the very next frame, after you moved 2 units up, and if yoh haven’t given another MovePosition command, then you will start moving using your velocity
can I use quaternion.lookrotation?
in 2D it's usually not what you want
then I honestly have no idea how to rotate object to its moving direction
transform.right = moveDirection;
i tried with transform.right, rb.moveRotation and thats basically all im semi famillar
when i do this my enemy jitters like crazy
because transform.right messes with rigidbody or something
then something like
var dir = rb.velocity.normalized;
float rotation = Mathf.Rad2Deg * Mathf.Atan2(dir.y, dir.x);
rb.MoveRotation(rotation);```
this is assuming it's a Rigidbody2D
but loup@snoop said that rb.moverotation overrides all my movement calculations. I mean it works fine but im kinda worried that its gonna bit me in the ass in the future
it is
shouldn't
only rotation
so then this will work as good as this?
( rotation = target.transform.position - transform.position;
rb.MoveRotation(Quaternion.LookRotation(rotation));)
that will not work
MoveRotation accepts a float in 2D
not a Quaternion
and that quaternion wouldn't be correct anyway in 2D
it doesn't work. The direction just sometimes change
(its called in the update method)
MoveRotation belongs in FixedUpdate only
It will be interpolated if interpolation is enabled for the RB
alright its smooth now but its rotation so slowly, like excavator. Why is that?
I guess your object is not changing directions very quickly?
that would have to do with how your velocity is set, not this code
In my code there is no rb.velocity beside in this code
yeah, just rb.addForce
AddForce changes the velocity
that's the only thing AddForce does
I'd like to understand the issue exactly
This
ill record you this, wait a sec
here it is
and his rotation changes when he hits a wall
{
Application.targetFrameRate = 60;
SaveGameManager.LoadGame();
foreach (var loadable in _saveables)
{
loadable.LoadData();
}
OfflineManager.instance.OfflineIncome();
}```
I want to run `OfflineManager.instance.OfflineIncome();`, when foreach loop done. How can i make this?
Exactly what you have will do what you want
code runs in order from top to bottom
Yeah, i have a race condition problem i think cause it's not working right.
When i make like this
{
Application.targetFrameRate = 60;
SaveGameManager.LoadGame();
foreach (var loadable in _saveables)
{
loadable.LoadData();
}
await SomeAsyncOperation();
OfflineManager.instance.OfflineIncome();
}
async Task SomeAsyncOperation()
{
await Task.Delay(2000);
}```
is the data loading launching some async thing?
Yes
oh well that's a totally different question then
Actually, it's not loading async. Just i want it to make async
Should i remake all entire all saving system?
Or is there a way to just make sure all LoadData functions done?
await their Tasks, assuming they return a Task
does anyone have any suggestion on what should i do if i want to have a laser rotate to the player position(the player will be moving) at a certain speed?
note i have the laser working, i only need to configure the rotation.
thanks :)
Slerp it's rotation
I think you would want to use RotateTowards to make it always work at a certain speed
Unity just blue screened my pc. Wtf
Did you do a while loop?
Only void update
Blue screen is probably unrelated to unity.. I'd hope
Or I mean unrelated to your code in unity
it is defiantly unity. happened 2 times few seconds after i pressed play
The first thing that comes to mind is a GPU problem
That is odd, is your PC old?
but that usually just results in your display resetting and windows getting mad
'Item' does not contain a definition for 'Reload' and no accessible extension method 'Reload' accepting a first argument of type 'Item' could be found (are you missing a using directive or an assembly reference?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
can i get some help with this ive been working on this for a while, i think the issue is that i need to be getting the gun class from the item but i dont know how
mb one sec
I mean you should probably configure your IDE first..
also don't post screenshots of code
Reload is commented on the base Item class. You do not need to re-declare abstract methods in the inheriting abstract Gun class
i commented it out because i wanted to rework the way i did things to clean it up
i didnt want to keep adding functions to the item class when i inevitably add more item types
items is from what I can see, an Item[] or List<Item> (or any other collection), so it indeed cannot find a Reload() method on the Item class
If it was a Gun[], it would pick up the method fine
is there a way i can get the gun class from the item class?
Yes but that's just not using inheritance properly
If you have to type-check whether it's one of the many inheriting classes, you're doing it wrong
Inventories are a place where downcasting gets really tempting
if you just store a big List<Item>
"downcasting" is when you cast from Parent to Child
"upcasting" is when you cast from Child to Parent
an up-cast always works; a down-cast may fail (what if you have a Sword instead of a Gun?)
i will sometimes do that for really small things, in very specific little classes that only handle 1 or 2 items
never in an inventory
You already have Use and Use2 which seem like two methods for implementing some generic action happening on the item, why not use one of these? Or make another?
nope. but now it works fine
your right that makes the most sense
if you have a collection of objects with different code on them, then use an interface
thanks for the help guys
like
public interface IHealingItem { public void Heal(); }
(item as IHealingItem)?.Heal();
if (item as IHealingItem healer) {
healer.Heal();
}
if item is not an IHealingItem, the as is null, and the ? makes it do nothing.
If it is, then this calls Heal()
The code you had before the edit looked much better
there are a few ways tbh
But this is equivalent to downcasting after all
if you want to downcast, you want to at least make it smooth, and do it very infrequently
downcasting in general is mildly bad juju
you might get a few cavities, but your teeth won’t all fall out.
How do I reliably detect when a game object was changed in hierarchy? (added/removed/moved/renamed)
it can be either the child itself or some "root" parent
i don’t think you can
unless you ask the factory, and listen to the creation of everything
I am gonna mention that I mostly need it in editor, for runtime it's to-be-decided
which is a bad idea
i know of at least one idea, and that is unity editor event → hierarchy changed or something
unity doesn’t believe in useful events for you to use
I think downcasting feels less "evil" when you can perform a meaningful action with every single possible downcast, and when you cover all possible downcasts
...wait
that's just a virtual method call
🤔
I have to do it for the inventory system in one game, since I have a few arrays of presently-equipped items (melee, ranged, consumable) that new items need to be sorted into
Anyone knows a guide about how to voxelise meshes? With voxelise, I mean construct a boolean array where I mark true/false depending if the cell contains a mesh or is inside one.
want a proven solution, battle tested and performant? → look for a library that can do that for you
want a simple bruteforce idea? → for AABB of a mesh, for voxel size S, iterate 3d space with increments S (center of cube), check if point is inside mesh (there are libs for that), generate bool array
and in unity you can use mesh collider for checking if point is inside/outside the mesh
I mean, it's not that hard to find in google even... https://bronsonzgeb.com/index.php/2021/05/15/simple-mesh-voxelization-in-unity/
can soem one help me i want to W8 befor seting it true so it is not spaming atack or block i want to stop for some time before randomly desiding which animation to play (its for AI )
to wait in a coroutine use yield return new WaitForSeconds(time); as you are already doing elswhere
i tryed it as well but this is what keaps hapening
Without seeing the rest of your code we can only guess
but also your animation apears to be set to loop
and/or doesn't have a proper transition back to idle
mby that the problem
thx
probably should be using Triggers and not Bools
and with Trigger you don't ever need to manually set it back to false yourself
I'm having an issue with Interfaces where if a function in interface is not being used it doesn't create an error that you can only resolce through implemeting that function.
you've given it a default implementation which means that method is not going to be a part of the class that implements the interface, it is only going to be part of the interface (though a new implementation can be specified in the class)
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
Thank you that makes complete sense. Am getting the error now which allowed me to implement the function and solved another issue i was having as well. Thanks @somber nacelle
I'm reevaluating how I use state machines right now. I'm wondering if I've missed the point a little.
Each state has CanEnterState and CanExitState properties. I mostly just explicitly enter states -- if the player pushes the "punch" button, then the player enters the PunchState, and the PunchState tries to re-enter the IdleState after it's done
But this falls apart if I introduce a GrappleState that still lets you punch things while in the middle of it
now PunchState wants to return to IdleState, which is wrong
and ignoring that, even if there's a state like GrappleSlapState, that state still needs to explicitly know about GrappleState
so that it can return to it
you could store the previous state and allow states to transition back to that
That's one thing i've considered: basically a state machine with a stack
The tricky thing is that the machine could be interrupted at a weird point
like if you get thrown in the middle of GrappleSlapState
ehhhh sounds like the punch/grapple thing needs to be a different state than the regular punching
you should go straight to RagdollState and then eventually get back up into the IdleState
even if there's a state like GrappleSlapState, that state still needs to explicitly know about GrappleState
so that it can return to it
Not sure I follow this issue or why it's an issue
Maybe it's just not an issue, haha
When you say "know about" - you mean have a reference to?
Right.
generally I would use enums or have all the states be accessible from the StateMachine itself or the manager or whatever, which all the states should have access to
one use-case: I have a state for making a noise (you know, to distract a guard in a stealth game)
i want the player to be able to do this in a lot of contexts
it would be very silly to have a MakeNoiseState and a MakeNoiseWhileSittingState and so on and so forth
A "pure" state machine would do that. But for practical reasons yeah it wouldn't be a bad idea to pass in a variable of some kind to the noise state to tell it what to transition back to at the end
One alternative I played with once was to just have a multiple state machines
it kind of maps nicely to different body parts
like, if your head state machine is idle, you can whistle even if your body is busy doing something else
but that's kind of A Lot
Is there any way to get a file from the game directory? I remember we had to use the Resources folder some time ago, but nowadays I'm not sure.
Resources is used to load Unity objects by name.
It's not used to load files
You won't be able to load the files that are lying around your Assets folder when you build your game -- the imported data gets packed into a few big archives
so for example, I want to load a physics material to set it as default in my code (and not having it public), which technically is a Unity object
In that case, yes, you can place a Physic Material asset in a Resources folder
then load it by name
does using Resources still lead the files to be a little exposed? I remember people being worried that the files there weren't as compressed as other files in the game.
I would expect them to be packed in the same way as the rest of your assets
you know you can set a default physics material in the physics settings, right?
the individual files definitely do not exist on disk, because Unity doesn't actually ship the files in your Assets folder. it interprets them as data Unity can understand and ships that
I see, well resources is the way then, thank you for pointing it out
with the exception of StreamingAssets, which is just copied into the built game
if you worried about decompiling anything can be ripped
it is for a specific thing heheh
yeah I don't know why I even worry about these things, people nowadays just explore every line of code as well lol
exactly more important just to make the game
ok but what if I bikeshedded my state machines for another week instead
You only see a small glimpse of the code someone makes. It is reasonable to assume it is their style, and that if the style in this little glimpse is bad, then it's reasonable to assume that the rest of their project also has code that is bad.
so it is important to get into the fine details for that little time you have with someone.
last thing I worry about is someone decompiling my code to see some hacky solution I used to solve some problem a time ago lol
is anyone using the Unity 2023.3 beta and getting an issue where you can't make a serialised list of a custom serialised class?
want to sanity check before making a bug report
what is happening when you try?
Show what you are trying
Also double check there are no compile errors in the Unity console
Getting this:
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.PropertyHandler.HandleDrawnType (UnityEditor.SerializedProperty property, System.Type drawnType, System.Type propertyType, System.Reflection.FieldInfo field, UnityEngine.PropertyAttribute attribute) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.ScriptAttributeUtility.GetHandler (UnityEditor.SerializedProperty property) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.SerializedProperty newProperty) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.UIElements.SerializedPropertyBindEvent evt) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.HandleEventBubbleUp (UnityEngine.UIElements.EventBase evt) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
...
from this:
[System.Serializable]
public class SpawnGroup
{
public string Name;
}
[CreateAssetMenu(fileName = "LevelDefinition", menuName = "Definitions/LevelDefinition", order = 1)]
public class LevelDefinition : ScriptableObject
{
public List<SpawnGroup> spawnGroups;
public ILevelCellsProvider levelCellsProvider;
public void GetLevelCells(ref Dictionary<Vector2Int, LevelCell> cells)
{
levelCellsProvider?.GetLevelCells(ref cells);
}
}
Any compile errors in console?
Seems it's crashing when doing HandleDrawnType cause it passes it a null attribute, then tries checking attribute.applyToCollection without checking for null first
Nah, no compile errors
I am getting a persistent memory leak when it's trying to display the serialised data though, I don't think that's me though (nvm, it's not consistently doing that)
is there any way I can use my .net 8 library in unity or do i have to revert a crap ton of stuff to fit the older unity .net version
So one of my zombies is a navmesh agent who uses rootmotion movement. When I pause the game (timescale 0), I get a critical error where his navmesh agent synchronizer returns a ''velocity is nan'' error, probably as a result of division by 0.
What can I do realistically in this situation, other than not make my pause a timescale 0?
i'm almost 100% positive that you would not be able to. you likely have to target the same .net API that your unity version is or older.
of course you can always just test it yourself either by trying to use the library in your unity project or by creating a .net standard or .net framework project targeting the same version your unity project targets and see if you can use the library there
damn that sucks
the best option would be to simply not make your pause reliant on the timescale
i've gotten accustomed to all these new c# 12 features this is gonna be awful
I said other than that -,-
and yet it's still the best option
asking in the #🤖┃ai-navigation channel if you are having trouble with your navmeshagent
no I mean how would you handle the pause
you do realize you can create a pause mechanic that doesn't rely on hacks like setting timescale to 0
But YouTube said!
I'm sure it's possible, just with a lot of work involved
I need help with SphereCasts, I'm using one to detect the ground and the reason I'm using SphereCasts is because I want to get the nearest point of contact with the ground but I'm running into this weird issue I can't explain where the isGrounded bool flags false when you're near the edge of the mesh as shown in the video
Here is my code:
private void FixedUpdate()
{
isGrounded = IsGrounded();
}
public bool IsGrounded()
{
// Check point of contact with last collider in array
if (useSphereCast)
{
return SphereCastGround();
}
return OverlapSphereGround();
}
bool SphereCastGround()
{
Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
bool groundCast = Physics.SphereCast(origin, segmentRadius - Physics.defaultContactOffset, origin + gravityDirection.normalized, out RaycastHit hit, maxGroundDistance, groundLayers);
groundPosition = hit.point;
return groundCast;
}
void SphereCastGizmos()
{
Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
Vector3 destination = origin + (gravityDirection.normalized * maxGroundDistance);
Gizmos.DrawSphere(destination, segmentRadius - Physics.defaultContactOffset);
}```
*the extra gizmos sphere's are just for clarity, only the first red sphere is where the SphereCast goes to*
Well, if hacking is the only solution, don't use 0 timescale, use a very very very small number that is essentially zero.
yea that's what I was thinking
I guess that should do it
like .001
Even smaller
but you can't then necessarily pause the game and take a shit
Mathf.Epsilon
if even smaller, then yea I guess
That's why it's a hack. Technically someone can leave it running for hours. But that's the assumption you make: that nobody actually will.
yup doesnt seem to be working
that sucks now i've gotta rewrite so much 😭
my fault for assuming unity wasn't stuck using c# versions from the 1700s
try fixed update
for spherecasting
on the bright side, hopefully within the next year we'll finally get the move to the core clr which will bring latest .net support 🙏
i mean yeah ig
i personally can't wait to be able to use those with expressions instead of copying a struct just to change one of its properties and assigning it back. and generic math
Same thing unfortunately
UNITY IS ON C# 9????
HUHHHHH
that's not even file scoped namespaces oh my god
im gonna cry
yup. it's old lmao
how do y'all put up with this
at least you can target .net standard 2.1 in the latest versions of unity instead of still being stuck on .net framework
honestly idek how i didnt notice since i used unity for months in early 2023 working on a class project
oh it's so over
why is it internal 😭
It's the wrong assembly.
oh lol
I installed System.Runtime.CompilerServices.Unsafe.6.0.0 with NuGet for Unity because I needed to do some bad things to my data
i don't think i actually need that anymore..
Unity has UnsafeUtility which has some, but not all, of the same methods.
damn doesnt have ReadUnaligned
unsafe unsafeutility really unsafe
or any of the unsafe methods i need
why did i not try this beforehand ughhh
no dudep
unity is on C# 7 with support for SOME C#9 features
even worse
i like it. change scares me, and John Riciotello protects me from it
It was my fault
for stupid reasons I have a package that I forgot has custom editors for base primitive types and it's not setup right for the 2023.3 beta
when later C# mentioned “we have a way better garbage collector”, my first thought was “Oh no! But muh memory garbage!”
but then the Unity devs came to the rescue and said “Not today, foul fiend! We’re staying the same!”
and everybody clapped
unity chooses to keep you in the past as you'll be too powerful otherwise
Is Unsafe.ReadUnaligned different from UnsafeUtility.AsRef?
typical unity dev
i believe so
comes in to work wearing mammoth furs and animal bones under a labcoat
||my wife was right that no one would get the reference||
I need help with SphereCasts, I'm using one to detect the ground and the reason I'm using SphereCasts is because I want to get the nearest point of contact with the ground but I'm running into this weird issue I can't explain where the isGrounded bool flags false when you're near the edge of the mesh as shown in the video
Here is my code:
private void FixedUpdate()
{
isGrounded = IsGrounded();
}
public bool IsGrounded()
{
// Check point of contact with last collider in array
if (useSphereCast)
{
return SphereCastGround();
}
return OverlapSphereGround();
}
bool SphereCastGround()
{
Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
bool groundCast = Physics.SphereCast(origin, segmentRadius - Physics.defaultContactOffset, origin + gravityDirection.normalized, out RaycastHit hit, maxGroundDistance, groundLayers);
groundPosition = hit.point;
return groundCast;
}
void SphereCastGizmos()
{
Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
Vector3 destination = origin + (gravityDirection.normalized * maxGroundDistance);
Gizmos.DrawSphere(destination, segmentRadius - Physics.defaultContactOffset);
}```
*the extra gizmos sphere's are just for clarity, only the first red sphere is where the SphereCast goes to*
origin + gravityDirection.normalized is not a reasonable direction to pass
You should be using gravityDirection.normalized
try regen project files?
show full stack
it's fine i just fixed it
destroyed this library for unity anyways what's a little more
nothing to do with code , it goes in #1180170818983051344 if anything
Not to mention that decompiling games isn't really a legal topic here.
hey i am using the Quick outline too from the asset store,
it is giving me 2 different results i gamemode view and build
any 1 know why this is happening
better to ask on the asset store page
in my webgl slots game, am I benefiting a lot in terms of performance on mobile browsers by avoiding using the Update method? I have most of the game done using events and coroutines
it depends what you're doing inside of those updates, also coroutines are effectively using update
events can help if you are doing a lot of polling but it's such a micro performance unless you've a lot happening
ah okay, it just some of the things that I had found myself adding to the update method, even though probably trivial, seemed really unnecessary to check every frame given the game is basically "on pause" unless the user clicks the "spin" button
of course i'll probably have to use update method sooner or later when i add some small background animations i'm planning on 🙂 . thanks for confirming it wont hurt
if anything just return early via flag
public Update()
{
if(paused)
{
return;
}
}```
tried did not get any responds
when using Transform.TransformPoint, how does Unity convert the vector3 from local to world ?
from "what" does it take references ?
from "what" does it take references
what do you mean by this? because you call the method on an instance of a transform which naturally has information about its local space
oh my bad, i thought the Transform wasnt a instance
well its perfect
the method is not static so it must be called on an instance
Keep in mind, every gameObject has a Transform
ew why are you nesting switch statements like that?
because i have to
well ofc there is always another way, but its working great until now and i dont want to remake the part of my system
at the very least extract that inner switch statement into another method
what does this change ?
then your inner switch can do its thing and you just break in the if statement
it will also make it significantly better to read the code
Nested switch statements is a huge code smell
On top of this mess, cant you already collapse the statements? Why use regions here
I can't collapse cases, only whole switch
how different is the code inside of the other case that these need to be such huge blocks for each switch case?
On a the switch _verticalstate each case is totally different
No reusability
I sometimes nest switch for performance
You need goto
For performance ?
i use goto when I cant bother to fix my logic
this is why assembly is the best language
For now i dont need goto
But i'll keep this in mind
For the machine, whats the difference between nested switchs, and replacing the nested switch by a function with the switch inside ?
Im on phone so i can't illustrate my example sorry
If you need to reuse the nested switch then better to put it in other function
I usually just put it inline unless it is too many lines
To prevent function call
Well the one in screenshot isnt reused
woohoo! I wrote my first working Event (in Unity). "It's not much, but it's honest work"
it would still benefit from being extracted into another method, purely from a readability standpoint. don't make your code unwieldy and impossible to read in the effort to maximize efficiency for a 0.0001% gain in performance
I have a script called SpawnManager.cs which spawns enemies. I have a gameObject with the SpawnManager.cs attached, and when I disable the script duirng runtime (with .enabled=true) while keeping the gameObject (that the script is attached to) active, the gameObject continues to spawn enemies. However, I need to keep the gameObject active, but I want the script to stop spawning enemies. How do I do this?
Make a variable that determines if it should do the spawning or not
hmm, .enabled=true does not disable the script
Hello, what is the purpose of VideoPlayer.waitForFirstFrame? What sort of issue it's trying to avoid?
Did you read its documentation?
Hi all, has anyone managed to create an Event bus / EventManager pattern with the new Awaitable methods?
ah I see. I wonder if it's useful if I didn't use playOnAwake or is it only useful if I use playOnAwake
Hello everyone, I have a question that I have not found an answer to. my game will be a multiplatform. based on the type of device it will run on I would like to change authentication. I can’t find any method in the system-info that reports what type of device is running my game. the operating system is not enough because different devices could have the same OS. can any of you suggest a way out for me? My has two mater device PC and Oculus
typically you would separate functionality for your different target platforms using preprocessor directives for conditional compilation
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
so i create a third person character using a character controller, but it wont going down, it can goes up to mountain but cannot go down. i add rigidbody but my movement becoming so weird
CharacterController and rigidbody do not mix. but you also need to show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this was my code, if it cant use rigidbody how can i make it go down ?
how to post a code?
you can manually apply gravity to your charactercontroller
ah i see thx
there are plenty of examples of how to apply gravity manually if you need a tutorial. you can check out any FPS movement tutorial that uses a charactercontroller to see an example of how to do it
Does anyone know a consise way to convert 1-9 numpads into ints?
Thanks a lot
For reference, i want to choose an inventory slot by pressing one of the numpads
you can cast
int i = (int)KeyCode.Keypad0;
For me that just returned 256
yes, that is an int
What i meant was that i want to press numpad 5 and that would return int 5
you can then subtract (int)KeyCode.Keypad0 from the int to get the number on they keyboard key
well, you should have said
Oh i see, thanks
Good morning, I'm doing a project where I have to get on a vehicle, once I get on I update the transform position, and the transform rotation with the seat transform, but this makes the camera shake when I move the vehicle left and right, thanks in advance
Does anyone have any idea how I can prevent this from happening?
Your description is way too vague for anyone to know what's going on
Hey I'm having some issues with the (new) input system, I'm following a Brackeys tutorial to get stuff to work but it doesn't seem to be detecting my inputs, here's my code:
Then jump simply outputs console text to verify whether it works or not
is the component attached to an active object in the scene?
Yeah the script is attached to my player object
But it wouldn't let me drag the input manager object into the InputMaster object
and have you saved the input action asset so it generates the c# class
I need the player and camera to move and rotate with the vehicle, but I'm doing something wrong because the camera flickers
you have saved it after assigning a binding to the jump action, right?
The input window itself has auto save checked
So I assume so
then congratulations, it works
It's not outputting anything to the console though
then you've missed one of the steps i have outlined
screenshot the inspector for the object with the component that instantiates your InputMaster class
Is Debug.Log still the right way to get stuff in the console
yes. otherwise i would have pointed out an issue there
Wait no, you're quite right
I'm not sure what the connection here to the active object in the scene was
looks like that's probably the issue
If this is the master object
What component do I attach
this component
then start play mode, open the console and try jumping. if it still does not work take a screenshot of the entire unity editor with the console window visible and that inspector visible
also make sure you unfold the binding here and check that you have bound the correct key(s) to it
Still nothing!
Have done this - I'll send a screenshot just to be sure its configured properly
Hammering space and nothing is happening
can you post the full class in a bin site
for the PlayerMovement component, that is
Yeah sure, I'll just paste it here since it's really not that long
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
// Reference to the CharacterController GameObject
public CharacterController controller;
public InputMaster controls;
public float speed = 6f;
// Update is called once per frame
void Update()
{
}
void Awake()
{
ConfigureInputManager();
}
/// <summary>
/// Method assigns delegates for each action mapping in the InputManager system to a specific method that they are supposed to invoke.
/// </summary>
private void ConfigureInputManager()
{
controls = new InputMaster();
controls.Player.Jump.performed += _ => Jump();
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
/// <summary>
/// Method handles the logic associated with allowing the player to jump
/// </summary>
private void Jump()
{
Debug.Log("Jumping now!");
}
private void Move(Vector2 direction)
{
Debug.Log("Ping" + direction);
}
}
sprinkle some more logs around and verify that code is actually running. if you have verified it and you have confirmed you are pressing the correct key at runtime then try restarting the editor because there is nothing here that would indicate it shouldn't work
Sounds good
thanks for your help
Why not just make the player a child of the vehicle?
On restart I got this:
This might be some clue to the problem
yeah you have to actually enable the input system. that should have popped up when you initially installed the package
I'll see if that rectifies it now it's restarted again - I did check with a debug.log in Awake() and it called immediately
Yep it's working!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@cosmic rain https://gdl.space/erifumucib.cs
On the main Thread i have a coroutine that updates the Dictionary<>
Yeah, I was right. You can't add/remove to/from a collection, when you foreach it.
Nevermind I didn't read properly. Let me have a look again in a min.
What line is the error thrown at?
On the foreach
i think the problem is that i'm updating the dict while i'm looping through it
I don't see you adding to chunks in it. Unless nearChunks references the same dict.
Does it?
Nope i update chunks in a coroutine https://gdl.space/
Hmm... Perhaps it is related then. Did you try the concurrent dict yet?
Not related to your problem, but the whole completion source is unnecessary, you can remove that.
Not yet, first i need to understand how to use them and how they works 🙂
I use it to know when the Task is completed and to get the results.
When i Run a task how do i know when it has finished to get the results?
This is What i still dont understand
i got a problem with my PlayerInteract script in unity, i dont know if this is the place to ask for help but i dont know where elso to ask, the error message is: Assets\Scripts\PlayerInteract.cs(29,73): error CS1061: 'Interactable' does not contain a definition for 'promptMessage' and no accessible extension method 'promptMessage' accepting a first argument of type 'Interactable' could be found (are you missing a using directive or an assembly reference?)
And the Script is here:
start by configuring your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Try running it as a main thread async method. If you get the same error, the concurrent dict is not gonna help.
async Task<int> DoStuff()
{
var tcs = new TaskCompletionSource<int>();
await Task.Run(() =>
{
tcs.SetResult(42);
});
return await tcs.Task;
}
Can be simply rewritten into:
Task<int> DoStuff()
{
return Task.Run(() =>
{
return 42;
});
}
With .Run you can't really. You need to return or await it.
Or you can set a field taskDone or something and check that.
The Code i wrote is the same as in the tutorial i watchen and it still doesnt work
you missed something. but you need to get your ide configured if you want to get help here
what do you mean by that?
#archived-code-general message
having properly configured tools is a requirement to get help with your code here
Right now i do like this https://gdl.space/qaxadojawa.cs
Thanks i will try
the external script editor is now set to "Visual Studio Code"
do you see red underlines in your code now?
no
then you did not complete all of the steps
Thanks it works and the code is more clear ❤️
how do i find the Common7IDE ?
well that's just the wrong set of steps entirely
follow the instructions for VS Code which is what you were using
If you want to understand why, starting from your original code:
async Task<int> DoStuff()
{
var tcs = new TaskCompletionSource<int>();
await Task.Run(() =>
{
tcs.SetResult(42);
});
return await tcs.Task;
}
Notice that because you are awaiting Task.Run(...), by the time that task is done, the result of tsc must have already been set, so awaiting tsc.Task is redundant. So you can instead rewrite it into:
async Task<int> DoStuff()
{
var result = 0;
await Task.Run(() =>
{
result = 42;
});
return result;
}
But notice that Task.Run has an overload that takes Func<T> and returns Task<T>, so you can further rewrite that:
async Task<int> DoStuff()
{
return await Task.Run(() =>
{
return 42;
});
}
And lastly, a pair of async/await is redundant, so you can remove that, and arriving at the final version of:
Task<int> DoStuff()
{
return Task.Run(() =>
{
return 42;
});
}
Your original code also has issues with exception handling which will hang the task, but yeah simply use the final version.
(A pair of async/await is technically not redundant and removing it will affect stacktrace, but in this case it shouldn't be an issue but you can also keep them)
thank you very much
Have you guys ever needed an object to know some position, but sometimes that position could just be a static Vector3, and other times it could be the transform of a gameobject?
Would you create some kind of interface that just returns a vector3, and the implementation can handle the source?
Something like
public interface IPositionGetter
{
public Vector3 GetPosition();
}
public class TransformPosition : IPositionGetter
{
public Transform transform;
public Vector3 GetPosition() => transform.position;
}
public class Vector3Position : IPositionGetter
{
public Vector3 position;
public Vector3 GetPosition() => position;
}
Or is this just silly, and I should just make sure whatever position I want to track has an associated gameobject?
so you can do
Vector3 v3 = ((IPositionGetter)someClass).GetPosition();
yes, makes perfect sense
That's a whole programming pattern: wrapper/adapter
the beauty of interfaces, the receiver is not bound to the source implementation only the results of it
anyone got a good script for animal walking ?
I know it just seems... overdoing it I guess. I mean I could literally just toss a Func<Vector3> as well.
the pattern is valid, only you can decide if it is worth implementing it in your use case
Instead of a method of GetPosition(), you can also make it just a property with getter, that will simplify Vector3Position or any implementation that stores the position directly.
It's also the reason why the convention is "public properties, private fields" because interfaces can contain properties but not fields, so if you need to refactor by adding/removing interface, you don't need to change your implementation.
But in Unity that convention is, kind of being ignored.
Interface cannot have fields.
Sorry mistyped.
it's a shortcut, technically there is no difference
Yeah properties is just "a field + getter/setter generated for you by compiler"
I know how you feel, unless used correctly properties are overrated imo
Really hate how Unity can't serialize properties.
It can.
real hate how Unity uses properties for structs
but what if I wanted to
Why not?
well, then targeting the backign field with attributes is going to be a hassle
It's just [field: SerializeField] though, one extra word.
Oh shit I did not know this.
yes, but stuff like [FormerlySerializedAs] and other attributes require directly targeting the backing field
Sure, but I feel like that's more of a tradeoff than a simple don't.
that might be a concern in App dev, it should not be in Game dev
Well, that's just a basic example, but if you were going to use one of the many editor supporting attributes
then dont use auto backing fields
I know they make the scripts look cleaner, but you may end up even with more lines of code if you want to integrate any of it
A lot of properties' powers are unfortunately not applicable to Unity, either because Unity's design or Unity stuck in C# 9. It's really sad comparing to regular .NET, can't wait for the Core migration to come.
whenever that happens
😔
Unity devs were just very inexperienced in C# when they made the move to it and has been stuck in the shit hole they dug ever since
Partly they also had to support UnityScript and Boo at the time.
I remember
no it bloody well wasn't
Heyhey.
This is how play audio when the curser hovers over a uibutton. If you exit and enter the button really fast, the hole sound becomes more quiet. (The background music too, etc).
I don't know much about sound in unity. What is happening and how do I prevent that?
Code: public void CarryOneShotAudioSource(AudioClip audioClip, float volume) { oneShotAudioSource.PlayOneShot(audioClip, volume); }
any one know how to make a camera tilt like this one ? https://www.youtube.com/watch?v=5eWgx5quetk
Hello,
I am starting to develop my retro FPS game. I will add more videos in future from progress in this game. These videos are not as tutorial. In case of your interest, you can follow progres in my game or leave your opinion. Thank you! #unity3d #gamedev #indiegame #retrogames
Just rotate it in its Z axis
You can use an empty container object/parent that you rotate
Hello,
I have some problems with unity old Input system (for some reasons for now i can't changed it even if I want...).
I have game where controls is with KeyCode.RightAlt, LeftAlt, RightControl, LeftControl
But for some reasons Unity is using RightAlt as LeftControl (Altgr)
Is there a way to prevent it?
Perhaps a keyboard layout issue?
Sadly not. It's not only on my keyboard. Tested by few people.
Related posts i found was:
https://discussions.unity.com/t/why-does-input-getkey-keycode-leftcontrol-returns-true-when-i-press-right-alt/172454
Hi there! I am working on a remapping system and I found a weird issue: pressing the right alt on my keyboard lead to those two functions to return true: Input.GetKey(KeyCode.LeftControl) Input.GetKey(KeyCode.RightAlt) I thought it was some weirdness linked to my build or to my code, so I checked on another computer: same issue. So I wrote t...
Have you submitted a bug report?
And have you seen if the new input system has a similar issue?
No, like i said, for now i can't use new input system.
I haven't submitted any bug report (i don't think they will resolve it any way, they are working on new input system) yet,
for now i was looking for some information, maybe somebody has similar problem, or information if this is intended behavior.
Looks like you found some people with the same problem
My recommendation is to submit the bug report, they absolutely still support the old system, and see if the new system can bail you out in the meantime
Ok, i'll do this. Thank you very much for talk!
Hey guys, I have a problem with my game and I'm trying to do the tutorial (https://youtu.be/KqpMOdPj3co?si=mzAWb3PSkehjclJP&t=1376) and from the movement part I have a problem and I use a Unity asset (https://assetstore.unity.com/packages/templates/systems/low-poly-shooter-pack-v4-3-54947) and now I have to somehow recode it so that it becomes exactly as networking as in the video I worked on it for 1 week so 5 days xD and can't do it and I'm so desperate I even tried with ChatGPT but never got anything working out now I want to ask if someone who knows it very well would do it for me would be very happy and very supportive, you can also write me a DM
In this tutorial series I'll show you how to create an online multiplayer first person shooter with Unity and Photon Fusion from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/multiplayer-fps-65725126
📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames
In this ...
there's no actionable question here
the assembly def takes all files in folder and all files in subfolders (except if those subfolders have their own assembly def) correct ?
yes
weird
i have the following:
somefolder /
- main.cs
- assembly definition file
- somesubfolder /
-- otherscript.cs
inside main.cs I can't get the class of otherscript.cs
mb i updated
show the code?
and what error you're getting
Also is the error only in your IDE or is it also in Unity
maybe its VS ?
Yeah Misc files means your VS is not configured
That should say the name of the assembly
Alternatively regenerate project files in Unity might have helped too
fibwizzle
I need to make 2d platformer pathfinding
this may be a challenge
the left and the right shouldn't bee too hard, but verticality is where the challenge emerges
I might just have "jump points" which dictates where creatures can jump and each creature has different types of points they can use
actually, I could probably do this without that provided I don't use floating platforms
or at least minimize the amount
you can’t have a platformer without platforms
you can, but that is core to the genre for a reason
nuh uh
actually I can make floating platforms work I just need a trigger below the platform that has the same flags
can you represent everything with a grid?
its already on a grid
tilemap
its cool ive figured out how to do it tho, I got this
good luck
btw, if it’s pathfinding, I would recommend having a representation of the level as a grid, as a directed graph
anyone knows how to copy a sprite properly in a editor script? since it is made out of 2 assets (main sprite asset and texture2d), just copying the sprite asset keeps the reference to the original texture asset which I also want to copy. also, it turns into a .asset file while the original one has import settings in the meta file
what do you mean by copy?
you want a deep copy, as in a second new sprite asset in a separate file?
I used that method, but as I said it just creates a .asset file
What's wrong with that?
I guess I'm curious why you want/need to copy the original image too
i would expect the copy of a .asset file to be a .asset file
you dont copy the sprite you copy texture
sounds like the machine is doing what you asked it
the "sprite" is simply a rect of the area of the texture
it is generated automatically by the importer
This is what is inside the .png.meta file
fileFormatVersion: 2
guid: 9b1f67d458d836e4f9528346efccfa50
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
I want to copy it as a single file
well, sprites are sliced from textures
I think it is a separate asset, not just a texture
if you want the texture to automatically import as a sprite you can write your own import post processor and flag the texture for reimport as a sprite
its not, by default an imported image generates a texture object and a subasset sprite
i think he might be wanting to make a duplicate texture, and also have a duplicate of the sprite asset targetting the new duplicate texture
correct me if i’m wrong
but a lot of this is confusing tbh
that is what I would do if I have no other choices, but if possible I want to use the texture importer
well, what is it that you DO want to do
what should your editor script do?
lets say I have a texture, and a sprite is sliced on it
basically have the sprite in a single png file, with the meta containing the sprite info like this
uh, why do you want a sprite in a separate single PNG file?
it is used to create custom user made levels. one part of the editor is responsible for choosing the thumbnail. I need to copy it to a local folder. it should not be located anywhere else
local folder on user machine?
thumbnail as area of the level rendered into an image?
yeah, that is standard
are we talking unity editor or custom runtime editor?
i wonder if you need a screenshot tbh
hmm
CanJump = Physics2D.Raycast(transform.position, GetLookDirect(), 0.0001f, 3);
this seems to always be returning true even when no objects with that layer are anywhere nearby
users use unity editor as an sdk?
a screenshot might be easier tbh
yeah, by using addressables to export levels
any idea why it is doing that?
ok i wont dig into it myself, what i would do is i would first - check if its possible to grab the sprite sub asset, modify it and see if the asset picks up the changes as is
nevermind other people need more help
second i would write a custom post processor that would be told that this next import should be a sprite type
it would be better if I just copy both assets
raycast doesn’t return a bool
and upon importing the duplicated image it would switch it to sprite
oh
why tf did it let me assign it to a bool then?????????
probably casted the int to a bool?
lastly in the same post processor it would just copy the values from reference sprite to the newly created
it returns an int????
hmm
probably with EditorApplication.delayCall after import is complete
also, you should never ever use physics queries without a proper ContactFilter2D
I may try that, thanks
you can also specify layers, but the query takes longer the more objects of that layer are roughly in the zone of the query
so if you don’t specify layers, shit gets really expensive
yeah i'm just doing layers
which will work for me, I don't need to optimize too hard rn
no, I specified layer 3 which is my ground layer
yes
I think so?
and 00000011 sounds like TWO layers, which have default values
layer mask and layer are two different things
oh huh
ok
layer 5 would be layer mask 2^5 or something
it’s offset by one. i don’t remember exactly right now
i'll just use a set one then
but I use the ThunderNerd Layers and Tags plugin so I just have a class with consts defined for layers and layer masks etc
then you can call Layers.GROUND_MASK or something like that
and it gives you the layer mask for that layer
Layer 5 would be int mask = 1 << 5
right, cause 000001 is mask for layer 0
point being, since both are easily cast with ints, it’s very easy to forget that you can have a layer vs layer mask
layer mask 3 = 0bx0011 means search for layers 0 and 1
The codegen approach you linked is neat I like it
thanks. it’s extremely handy
I made my own static (non generated) class to accompany it, btw
StdContactFilter. It has several public static readonly ContactFilter2D which consolidate specific queries that span multiple layers
How do you use multiple layers with it ?
You still need to | them manually
Or feed them one by one into a utility method
eg public static readonly ContactFilter2D floorToPlayer = new ContactFilter2D() {
layers = Layers.GROUND_MASK + Layers.SOLID_TO_PLAYER_MASK + Layers.SOLID_ENTITY_MASK,
useLayerMask = true,
useTriggers = false
}
you also have auto generated layers, like Layers.GROUND would be the (non mask) layer of ground
so it gives you the mask or ID representation
i forget the exact syntax, but it’s something like that
so whenever I add new layers, I can just modify my static class
my code references the StdContactFilters, and not the Layers class, usually. To keep it centralized
hey guys. i am trying to make a simple enemy platformer AI. So it basically moves left to right and flips if colission or fall off. However this moving between two points can be reused for flying hazards or such. Any tutorials/advice on how to approach this to make my code reusable in the future?
copy the component into new empty project
work from there understanding which dependencies it has, and how to minimize them, minimum dependencies, encapsulation, component being agnostic of its use
Sounds fair
would using these "AI" movement classes only to calculate next desired position work? and then just let these hazards or enemies generate an AI for themselves
not sure what you mean by this
let these hazards or enemies generate an AI for themselves
create a new non monobehaviour class from within themselves
give it parameters such as leftmost bound, rightmost bound and speed
and then use that to calculate movement
basically i want reusable movement in multiple hazards/enemies
Hello, my AI character walks backwards, how can I fix that?
Well that's going to depend on the details of how your AI character works and is set up
its a common thing to do with waypoint systems and the like, but its better not to avoid using components as waypoints for it, makes it easier to work with, however if you really need it you can write a custom inspector with transform handles that allow you to move your waypoints (which are just vector3 serialized in the mono) with a transform gizmo
for an example of that you can look at LightProbeGroup built in component
or BoxCollider for modifying extents of bounds
all those manipulators are done through Handles editor class
I asked him to follow the player by the code: agent.SetDestination(player.position);
sounds like your 3D model is backwards
problem is that you will have to handle absolute/local coordinates, so if you serialized in local and moved the AI the points would move with it, can be desireable in some cases, may not be in other, a toggle that converts those would do tbh
similar toggle is in LineRenderer i think
and how would you advise handling colissions? would these enemies have a rigidbody, or should i give them an interface that the player checks on collissions?
i cant give you a definitive advice on that, any method has pros and cons and its up to you which you prefer, any of them will work
Do You think I have to rotate the model?
I think you have to re-export it with the correct settings
you can edit the prefab so that you have a transform between the root and the GO with animator, and then rotate that transform
I created the model with pro builder
then you created it backwards
make sure the blue arrow matches with the "forward" direction of the model
(when in local rotation mode)
I Will check that
You are right, it do not manches. The problem is that if I rotate it the animation works backwards.
I Will try that
Then you have to fix the animation too
I Will have to do it again or there is a faster way of fixing it?
You were right! I have solved it. Thank you very much! 🙂
oh ok
Hello, how can I make a code to detect the closet enemy?
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Then loop through the result to find the smallest distance
Hello im kind of new to game programming. i had an idea that im working on more of a challenge and working out an idea that a full game. basically im having an issue with creating a dictionary of assets that are beeing instanciated through a manager script. the issue is each instance game object has a player stat, and I need this to have permanance through scene change. and the game objects are retained when switching back to the scene. im a bit lost with this one.
ive tried json serialization and dont destroy on load and not real luck
Thank you
dont destroy onload should work for you, what was the problem with it?
When I do dont destroy on load I either cant unload the objects on scene switch, or reload the objects switching back to the scene
yes, but that is required behaviour if you want permanance
so dont go down the rabbit hole of serialize and deserializing the data?
you can but it's unnecessary in this case.
another option is to maintain a set of POCO's in a singleton with DDOL
what is POCO?
Plain Old C# Class
not needed
so how do I set up the object to be unloaded on scene change and then loaded back in? not sure if you have a good doument link on this.
ive been looking for a bit.
lets make a thread and I'll explain
hey all, so i just tried converting to URP. IT worked kind of as expected? except for the fact that my textures did not turn dark, and lighting is not needed to see anything after this conversion. Any tips? i want to add lights to my 2d game
I used window -> rendering -> convert built in to URP
unity editor 2021.3
Hi!
I have like 30 draw calls that draw characters on my scene. The textures are separate files for every part of the outfit. Looking for a way to reduce these draw calls, would having all textures on Sprite Atlas reduce draw calls to like 2?
I am using the virtual camera of Cinemachine, but sometimes the camera changes the Position to some weird place and because of the CinemachineBrain I am not able to change this. Simply turning the CinemachineBrain off and on again doesn't work.
Sprite Atlas is extremely easy to setup in Unity.
https://docs.unity3d.com/Manual/SpriteAtlasWorkflow.html
However, you must also have a single skinned mesh renderer if they are skinned.
So, yeah, in your case I believe it is not possible to batch them without recreating the mesh data at runtime.
hm, all outfit parts are separate
The alternative, would be to use solution made for that but they are not well supported.
An example would be: https://www.youtube.com/watch?v=_GGVlzAcWgA&ab_channel=Dr.ShahinRostami
okay thanks, I will check that 😄
Do not lose too much time on that
public void ChangeLanguage(string localeName)
{
var targetLocale = LocalizationSettings.AvailableLocales.Locales.Find(x => x.LocaleName == localeName);
if (targetLocale != null)
{
LocalizationSettings.SelectedLocale = targetLocale;
}
}```
Why does this not work for changing language with the Localization package ?
at a guess localeName does not match any known LocaleName's. you could try doing some debugging
yes but what is the common code to change language ?
Hello!, could someone help me with Firebase Functions? I'm trying to implement Push Notifications in my app, but for some reason, I'm not receiving any messages.
This is the code I use in Unity to receive the messages:
[Link to Unity Code: https://gdl.space/quvefeyula.cs]
This is the code for my Firebase Functions:
[Link to Firebase Functions Code: https://gdl.space/nilapuzogi.coffeescript]
Hello everyone, I'm facing a problem and I don't know how to solve it.
I implemented an inventory system in my game. Every time I press a button, I can use the item equipped from the inventory. You can see the workflow right there.
public void OnItemUse(InputAction.CallbackContext context)
{
if (!context.performed)
return;
_currentItemSelected = Instantiate(_currentInventoryItem.ItemPrefab, _itemUsePosition.position, Quaternion.identity, transform).GetComponent<ItemBase>();
if (_currentItemSelected.GetType().IsSubclassOf(typeof(ThrowableItem)))
{
ThrowableItem throwableItem = (ThrowableItem)_currentItemSelected;
throwableItem.SetFirePoint(_itemUsePosition);
_inputController.SetupOnItemUseActions(throwableItem.BeforeThrow, throwableItem.Throw);
}
else
{
_inputController.SetupOnItemUseActions(_currentItemSelected.Use);
}
_inventory.Remove(_currentInventoryItem);
}
//
//For context
//
public void SetupOnItemUseActions(Action onPerformed, Action onCanceled = null)
{
_input.Gameplay.UseItem.performed += ctx => onPerformed();
_input.Gameplay.UseItem.canceled += ctx => onCanceled();
_input.Gameplay.UseItem.canceled += ctx => ResetOnItemUseActions(onPerformed, onCanceled);
}
private void ResetOnItemUseActions(Action onPerformed, Action onCanceled = null)
{
_input.Gameplay.UseItem.performed -= ctx => onPerformed();
if (onCanceled != null)
_input.Gameplay.UseItem.canceled -= ctx => onCanceled();
}
The problem is that, when I'm trying to use a throwable item, and I want to throw 2+ items in succession, all the items execute the BeforeThrow and Throw functions.
Here is a recording, demonstrating the problem https://youtu.be/YngQUFxsvtU
just from the video it looks clear that the items are not removing the listeners
ctx => onPerformed(); you'll need to actually define these delegates so you can remove them later
The same thing that i was thinking. But, with some debugging, I can clearly see that the ResetOnItemUseActions is executing
Can you give me an example? I'm not too well versed with delegates
e.g
Action myDelegate = ctx => onPerformed();
_input.Gameplay.UseItem.performed += myDelegate; // now myDelegate is subscribed
_input.Gameplay.UseItem.performed -= myDelegate; // now myDelegate is unsubscribed
alternatively, actually write your own method for it, e.g (I forgot the exact type ctx is)
void PerformedHandler(InputContext ctx) {
onPerformed();
}
..
_input.Gameplay.UseItem.performed += PerformedHandler;
..
or even better, change the signature on onPerformed and skip the middleman here
Help plz
I'm facing a challenge in my project using Quest 2 and Hand Tracking 2, where manipulated objects pass through others instead of interacting. When trying to move an object towards another, it doesn't stop but goes through. I use Unity and seek guidance to configure realistic collision detection between objects. I appreciate any assistance from the community to enhance this experience.
Best regards,
Ok, now is more clear. So, if i want to unsubscribe correctly from an action, i need to store the delegate that i passed to the InputAction, in order to let them be recognized by the -= operator
yes - the why being that the compiler will generate different internal methods for each anonymous delegate, so you're not actually unsubscribing with the same one
Ty. I will give it a try later
Hi all, does anyone have recommendations for a Redis client to use in Unity? I've tried adding NRedisStack https://github.com/redis/NRedisStack to my project but the csproj file doesn't allow adding packages via Command Line. Does anyone know of a solution or recommendation for this?
I'm trying to have the purple explosion VFX effects play once the enemy dies. The VFX effect consists of a light appearing briefly and then purple particles coming out. However, when the enemie dies, a shortened version of the VFX effect plays instead, where a light appears briefly, but no purple particles come out. I used manaDeathParticles.Play(); to make the VFX play
https://paste.ofcode.org/RFDeAKKVALLmVDK5hwtUyA I am trying to make an enemy patrol between an array of points but it is just standing still, here is my enemy in the inspector
is script running ? are you sure animator is not overriding positioning?
make sure that your animator is not controlling its position
let me double check that
it was that thanks
I am looking to spawn the prefab using one of the two red squares as its spawn point
normal though it just spawns with the middle of the whole thing as the center
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
you can specify a position and/or a parent object when you instantiate something
I see you can assign a parent but i dont see the part where you can specifiy the prefabs "pivot" point
instantiate has nothing to do with an object's pivot point. you can specify the position it spawns at though
would the prefab not spawn at the center of the position I specifiy
why don't you try it and see
because it definitely seems like you are confusing an object's position with its pivot point
Im trying to spawn several different prefabs using the red squares to be like cells
both spawn with an origin of 0,0
if you don't want it to spawn at 0,0 then tell it what position you do want it to spawn at. that's what i've been trying to get through to you
Yes I want them to spawn at 0,0. But i am looking for a way to have the red point always be at 0,0 when spawned