#archived-code-general
1 messages · Page 322 of 1
In the following code I am trying to flip a sprite based on an enumerator. However the flips don't get applied to the sprite.
Does anyone know what I am doing wrong here?
private void ShowSprites()
{
List<SpriteRenderer> finalSprites = new List<SpriteRenderer>();
foreach (var tuple in gameLogic.chosenBlocks.Values)
{
finalSprites.Add(AlterSprite(tuple.Item1, tuple.Item2, tuple.Item3));
slots[finalSprites.Count-1].style.backgroundImage = new StyleBackground(finalSprites[finalSprites.Count - 1].sprite);
}
}
private SpriteRenderer AlterSprite(SpriteRenderer texture, Flip flipOption, Rotation rotateOption)
{
switch (flipOption)
{
case Flip.none: texture.flipX = false; texture.flipY = false; break;
case Flip.flipX: texture.flipX = true; texture.flipY = false; break;
case Flip.flipY: texture.flipY = true; texture.flipX = false; break;
case Flip.flipXY: texture.flipX = true; texture.flipY = true; break;
default: break;
}
return texture;
}
I see no point in your List as you are doing nothing with it
Valid but that's because I updated the code. Just trying to have it functional
the obvious thing to do is add some debugs to AlterSprite as you cannot see from that code what exactly is being passed in
the returned texture is correct
let me send another screenshot
Updated the code slightly. Not the most elegant solution either, but got rid of the list.
int i = 0;
foreach (var tuple in gameLogic.chosenBlocks.Values)
{
slots[i].style.backgroundImage = new StyleBackground(AlterSprite(tuple.Item1, tuple.Item2, tuple.Item3).sprite);
i++;
}
I supposed it I call .sprite it accesses the source sprite and not the updated one
you do know that the flip variables only affect the sprite renderer and how it displays whatever sprite is assigned to it, not the actual sprite texture, right?
beat me to it
How do you suggest to go about it?
What I wanna do is show 3 sprites in my UI. Each of them altered individually by flipping or rotating
but with the same original sprite
Hello, I am trying to spawn multiple rooms randomly and use this code to check and make sure they do not overlap, but it work very inconsistently. Is there something wrong with my logic or should you not try to spawn mutiple rooms and check for overlaps on the same frame?
Hey everyone, I am wondering, if its possible to extent the gameobject class, so I can use a simple toggle method in the UI buttons? I kniow its working codewise, but it is not showing up in the dropdown, which I guess is the issue of it being a sealed class probably?
To clarify, I am using this in my extensions class, which is working in other classes of course. Any idea how to get it into the reflection of the UIbutton OnClick events?
public static void Toggle(this GameObject go)
{
go.SetActive(!go.activeInHierarchy);
}
you should be able to set slots[i].transform.rotation
https://forum.unity.com/threads/how-to-flip-a-visualelement-on-the-x-axis.954105/
since you aren't syncing the physics transforms and aren't waiting for physics to update then your physics queries won't have the most up to date information once you move those objects.
however it is generally better to generate the layout before spawning the rooms. then once the layout has been decided you just spawn rooms in the correct places based on the generated layout so you wouldn't even need these physics queries.
then I would have to do the opposite opperation for every time I refresh right? otherwise, when I show new sprites, the previous "transform" is added to it
no idea, you'll just have to experiment
Oh my god thank you! I just added Physics.SyncTransforms(); and now it works. Have been stuck on this for like two days 💀 . And yeah I now realize I maybe should have done it the way you recommended with generating the layout firtst but it seems a bit late now. Either way thanks alot!
Currently I'm trying to make a UI object use "OnMouseEnter" and "OnMouseExit" events for objects in world space.
It works fine unless my actual mouse cursor is left over any UI.
What could I change with it to make it detect those regardless of what the actual mouse is hovering over?
private void Update()
{
Position = new Vector3(_rectTransform.anchoredPosition.x + (Screen.width / 2), _rectTransform.anchoredPosition.y + (Screen.height / 2));
_colliderHit = GetCollider2DFromScreenPosition(Position);
if(_colliderHit != null && _colliderHit != _previousColliderHit)
{
_colliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseEnter");
if(_previousColliderHit != null)
{
_previousColliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseExit");
}
_previousColliderHit = _colliderHit;
return;
}
if(_colliderHit == null)
{
if (_previousColliderHit != null)
{
_previousColliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseExit");
}
_previousColliderHit = _colliderHit;
return;
}
}
private Collider2D GetCollider2DFromScreenPosition(Vector2 screenPosition)
{
Ray ray = Camera.main.ScreenPointToRay(screenPosition);
RaycastHit2D hit2D = Physics2D.GetRayIntersection(ray);
if (hit2D.collider != null)
return hit2D.collider;
else
return null;
}
here is a gif of what I meant
Nvm, it was an error with a conditional I made earlier
Has anyone ever gotten this error before, or knows how to fix it?
At a guess that is an authorization problem, HTTP 403 is, generally, a lack of auth
Yes, i somehow cant accass an file stored in the unity cloud, but the strange thuing is, that the compiled / published programm ran just fine for 3 weeks and today it soemhow startet to not work
hey guys, when i run code to move transform.position, it doesnt move the instance. but if i disable the animator attached to the character, then it moves the instance
when i turn on apply root motion in the animator then it works fine
expected, you can disable root motion in the model
but usually I make the model a child object of the player
oh god...
Move your post there as this is not a coding question
ye I know, fixing
Anyone know anything about asset bundling and storing assets in cloud to retrieve it on runtime using UnityWebRequestAssetBundle?
Should I use #if UNITY_EDITOR with Application.isPlaying to increase the performance when the game is played outside of the editor?
if you have stuff you only want running in editor then that could be useful yeah
you can also use the [Conditional("UNITY_EDITOR")] tag on methods
I see, thank you
Is there any way to make #if be shifted to the right as the other lines? It's fixed on the left.
Pretty sure that's impossible on vscode
I'm using VS. Do you know if it's possible there?
Anyone knows what if attributes created with CreateVFXEventAttribute are worth caching ?
Similar question, is it worth caching the System.Actions ?
things like System.Action setCoroutineToNull = () => _coroutine = null;
Depends on the context
You'll get less garbage allocated if you avoid creating a new anonymous function every frame
Storing it also means that you can subscribe to and unsubscribe from events with it
(this also applies to passing a method to a function that accepts a delegate type!!)
(i don't remember if it also happens for event subscriptions, but i'd expect that to be the case)
foo.Bar(MyMethod);
resolving the MyMethod method group produces garbage
indeed they do
subscribing to an event also generates garbage, but you get even more if you pass a method group
I have a system that sends requests to a singleton, which then does some work in a job and responds in the next frame by invoking a callback method
With a little more work you can skip out on EvenAttributes and just do graphic buffers with unmanaged data types reuse the buffers directly
I stick the callback method into a System.Action<TheResult> field in Awake
it winds up producing zero allocations!
it's not an event -- it's a List<Request>, where Request is a struct
an event has to be a lot more cautious; you can un-subscribe from an event while it's being invoked
Yeah i got it
yes, ColorType is not string
yes, that is the method signature required
yeah, on value changed take the value type of the element so Toggle takes a bool and Slider takes a float
Hey guys I have a questions regarding code structure.
So I have coroutines, some are called only once, some can be called from update.
I have added a bool to each coroutine which represents if a coroutine is active or not.
The problem is, once you have a number of coroutines, it's hard to keep track of each bool and routine.
Is there a better way to do it?
A Flags enum could be a better option
why not store the coroutines inside array of Coroutine[]
or list
bools seem wild use if you have many
If you store the Coroutine variable returned by StartCoroutine, and have the coroutine set that variable to null as its last act before completing, you can check if that variable is null or not to know if it's running, and also be able to do something like cancel it if you need to start it again
Hey guys, I'm having a lil bit of trouble implementing the rules for the day/night cellular automaton. I have the GoL and Seeds rules working, but for some reason the day/night rules aren't working. instead of showing what it's supposed to be showing, it is a chaotic growth instead. I tried replacing the day/night rules with the rules for the maze automaton, and it did the maze automaton perfectly- so the problem is certainly in the day/night rules. here is a bit of the compute shader with the rules in it: ```cs
if (current.r == 1 && current.g == 1 && current.b == 1)// GoL rules
{
if (GoLcount < 2 || GoLcount > 3)
{
next = 0.0; // Loneliness or overcrowding
}
else
{
next = float4(1, 1, 1, 1); // Survival
}
}
else if (current.r == 1 && current.g == 1 && current.b == 0)// Seeds rules
{
next = 0.0;
}
else if (current.r == 0 && current.g == 1 && current.b == 1)// Day/Night rules
{
if (DayNightcount == 6 || DayNightcount < 3)
{
next = 0.0;
}
else
{
next = float4(0, 1, 1, 1);
}
}
else
{ // if cell is dead
if (GoLcount == 3)
{
next = float4(1, 1, 1, 1);
}
else if (Seedscount == 2)
{
next = float4(1, 1, 0, 1);
}
else if (DayNightcount == 3 || DayNightcount == 6 || DayNightcount == 7 || DayNightcount == 8)
{
next = float4(0, 1, 1, 1);
}
else
{
next = 0.0; // Stay dead
}
}
(I hope I didn't just disobey a rule by sharing that much code 😅 )
some more explanation is probably necessary isn't it
DayNightCount == 6 on both sides does not seem correct. Also !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.
Hmm that sounds interesting. I should check it when I have the time
the "if (DayNightcount == 6 || DayNightcount < 3)" is to check for neighbors in that range. if there are any, the cell dies due to having 6 neighbors or less than three neighbors. the cell also goes from a dead cell to live cell if it has 6 live neighbors. here's the actual rule itself
(also thanks I didn't know you could put "cs" to format it correctly :D done it)
We're setting the targetFrameRate to 60, but we notice on high refresh rate monitors it is not respected. 180Hz shows 180 fps. This is on windows standalone.
{
Application.targetFrameRate = 60;
}```
are you certain this code is even running
also how are you checking fps
We're checking in a build with Nvidia app and Fraps
Ok but I dont see how this if (DayNightcount == 6 || DayNightcount < 3) implements the rules for survival
Are you using vSync
Vsync Count: Every V Blank
So yes
admittedly, I dont totally understand vsync
That will sync you to the monitor refresh rate
in what way? (I'm pretty sure you're onto something I just can't see it at the moment xD)
Or try to
thanks, so what would you recommend? turn it off?
oh wait I think I have something
the rules for survival are 3,4,6,7,8 but you implement survival as > 3 and != 6
just needed to change the == 6 to == 5
classic oversight
thank you very much for pointing that out!
hmm, I did say == 6 on both sides seems incorrect
yep xD
and that was without knowing the rules
yeppeye
I just needed to look closer
darn it
anyway, I'm sure I'll have more cases like these- I just need to look closer and analyse more :D
yep, plug in values and run the code in your head, simple errors like this soon become apparent
yep! thanks again!
hi! i'm having some trouble learning about instantiation. i'm currently working on a flappy bird clone... i've got the pipes moving across the screen but i want to have them spawn at varying heights once they move off screen. my question is how can i have the game instantiate a new pipe at a random height once it moves off screen?
currently my game just has the pipes move back to the intial x position when it moves off screen in its movement script
but ideally i'd want it to destory and instantiate a new pipe when it moves off screen
Instantiate can take a position, I suggest you read the documentation
Hi! I have 3 smaller projects and i would like to combine them to be able to use features from each of them, is there any good way to just fuse all 3 projects so that I can access the stuff i need and then later delete the rest?
sure, use Asset->Export Asset->Import
Export asset exports the whole project?
it exports what you tell it to
but do i handle the instantiation in a seperate script or within the movement script? sorry i should have been more clear with my question!
Sounds good, thanks!
tbh, it makes very little difference, do what is easiest for you
okay
hello i have a question ,i am a begginer can you make a modifiable excel file for player in unity
that would be a problem as I don't believe there is an Excel integration dll available for Unity
hmm so an external excel file is kinda imposible
not impossible but not easy without sufficient knowledge
Anyone know what to do about this?
Nothing I find online works.
I'm already set to VS 2022, tried regenerating project files, deleting library, deleting .vs file, deleting all the project files from the project folder manually, updating VS and VSTU, it just refuses to acknowledge that it's installed.
The one thing I suspect might be it is that I don't have Visual Studio Editor in my package manager, it doesn't show up even when I select All Packages.
I don't know if it's because it's not actually used anymore and the docs are outdated, or if something broke so that it doesn't show up for me.
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows
Could anyone maybe check their Packages/manifest.json and tell me what the package id and version for Visual Studio Editor are in theirs so I could try a manual import?
Not a code question @zealous jay Go to #💻┃unity-talk
Im trying to spawn enemies randomly on a 2d top down scene, but the enemies can spawn right next to the player and damage him right away, is there a way to check the disance between the spawnpoint and the player and spawn it further away if too close?
also is it possible to write data to an excel file from inside of unity in the game
same problem, no integration
ok thx for helping
If you are reffering to a .csv value you can do that without any problem. At the end is just like a long string where the value of each colum is split by a character ";" and each row end with an EOL "\n".
But you have to do the work to parse the data you want, this is an example of a script I use on a WebGL project : https://hatebin.com/dypbnbimep
i see thx for all the help
and how are you gonna get a csv value out of the Excel file?
You can export any excel file to a csv, that can be used by Excel program or any other text editor. I don't know if he is saying to use an xlsx file or any file that can be opened with Excel and will be display using the cell format
so a .csv file is NOT an excel file and would have to be made external to Unity not interally read/written in Unity which the OP asked for
I want to serialize a list of classes that derive from an abstract class to JSON, but it's throwing an error, saying that I can't instantiate the abstract class.
Can anyone help me figure this out? I've tried looking up stuff on it, but I don't understand it.
simple answer, cant be done. JSON knows nothing about the class it is deserializing so you cannot deserialize without exactly specifying the class to deserialize to
You'll need some ID to look up what class it was, then some mapping from ID to class.
Note that if you're just using the abstract class as the type, all you'll be saving is stuff relevant to the abstract class. Nothing from the derived classes
Gotcha
In this case, I'll probably just save a list for each derived class, then recompile them.
or use a decent binary serializer
Why is my game camera not showing up here? I'm trying to set the camera for the UI Canvas
You have the "Assets" tab selected, it won't show if your camera is on an object in the scene
(also not a code question, if you still have issues move your question to #💻┃unity-talk)
Input fields have a regex validation option if I remember correctly
Hi guys, I want to make interaction system, but it making ray only on X axis, not on Y, so it's working not correct, how can I fix it? Ray ray = new Ray(transform.position, transform.forward);
I need to change forward, but I don't know on what.
neither of those are X or Y
forward is Z
If you need to change forward, rotate your object. Currently it takes the local Z axis (blue arrow when you have the object selected) of the object this script is attached to.
transform.right?
Depends which direction you want
Forward is the object's z axis
I have an object, which has a BoxCollider2D with the size Vector2.one. OverlapBox detects the object when the point is shifted on 1 to any direction, when the size is larger than ~0.95.
Why such a huge offset? I expect it not to return any object when the size is Vector2.one.
Physics2D.OverlapBox(point, Vector2.one * size, 0f);
it's not helping
yep, i saw, but there is no things with both of them
Y/X
or Y/Z
wdym both of them
also this is like 3D game right ?
transform.right gives you the X axis of the object
It does not always "point to the right" of your screen, if the object is rotated for example
Don't mix up world coordinates eg. Vector3.right (which always points right) and object coordinates transform.right
it doesn't care about Y
i can look at the sky, but it will think that I'm watching pn item
in upper you see it
first of all put your gizmos in Local mode
you never want to configure this stuff with Global on
okay
gotcha, also send the code
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class Interactor : MonoBehaviour
{
private float radius = 0.2f;
public LayerMask mask;
public TextMeshProUGUI textE;
public void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
Debug.DrawRay(ray.origin, ray.origin + ray.direction * 1000, Color.red); // Отрисовка луча в дебаге
RaycastHit hit;
if (Physics.SphereCast(ray, radius, out hit, Mathf.Infinity, mask))
{
textE.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log(1);
}
}
else
{
Debug.Log(0);
textE.gameObject.SetActive(false);
}
}
}
this should just be
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red); // Отрисовка луча в дебаге
it is red ray in debug
i know what it is my guy
sorry, but i'm not native in english, what this message means
now that you put it in Local mode could you show the origin of the Interactor object
I was suggesting you change
ray.origin + ray.direction * 1000
to
ray.direction * 1000
I think thats what making your visual look strange when looking up
yes but its Local Z
is the Origin that has that script child to camera ?
show me the object that has the script
with whole hierarchy visible ,
which one has the script ?
FirstPersonPlayer?
if so its wrong
put it on the PlayerCamera
then which one had it
No way bro it worked!!!!
script is now on camera
Thank you a lot! Дзякуй!
Nah, my problem was too stupid and easy😅
Hi, does anyone know that I can implement IAP or other payment gateway sdk to my game but not related with google play store?
I think yes, because I know one game which you can download on GameJolt, but you can buy something
I will look for it, thanks for response
The problem is that I don't know how too add thing like that in game
I was searching through Google some payment gateway, but couldn't really find :/
hello i want to create a limited ranged of an ability in my game but i don't have idea of how to do that
!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.
also next time Don't crosspost
limited range in what sense, what do you want to limit ?
place = new Vector3(_Hit.point.x, _Hit.point.y, _Hit.point.z);
why this a new vector3 if it can just be place = _Hit.point
Do you know what game was it?
my script teleport my player I want add a to limit range like a spell in lol
so do a distance check
float dist = Vector3.Distance(player.position, rayhit.point);
if(dist <= maxRangeTeleport)
{
//Teleport
}```
You could also limit how far your raycast can go
Sorry
ForsakenAR
The issue seems to be caused by the miscalculations in the OverlapBox method. For now, I'm simply going to use the size of .95 instead of 1. If anyone has any better idea, please, share it with me.
It will detect any overlap, which naturally depends on the actual positions and sizes and rotations of your objects
All sizes and rotations are 1. This is also the distance between the point and the object returned
You'd have to show a picture of the scene and explain where the objects are etc
Gizmos.DrawWireCube may help you too
need help how to make when A game Over screen pops up and the player coudn't use controls walk when player IsDead = true; the screen works perfect and pops up but the player still can use the controls like walk
nvm
Disable your movement script or use a bool flag or time scale or whatever really
Many options
i replied to u
Is there an easy way to connect two rigidbodies using a joint through code? I'd just do it inside the editor but I can't easily get at one of them
You're right , apologies then. It got lost in the noise
Yep create the joint and configure it in code
AddComponent
I should specify, I can add the component to what I need, i just can't connect it to what I'd want to and can't figure out exactly how
it might be a bit more complex than it should be, actually..
did you get it working ?
OnEnable is called before Awake when an object is a child of another object?
Wasn't it supposed to happen in an order of Awake -> OnEnable?
https://docs.unity3d.com/Manual/ExecutionOrder.html
What is the solution other than placing all my objects in a root of my hierarchy?
Trying to run this code:
private void OnEnable()
{
Game.Instance.onInitComplete.RemoveListener(Init);
if (Game.Instance.IsInitialized) Init();
else Game.Instance.onInitComplete.AddListener(Init);
}
Game.Instance is null, even tho Instance is created in Awake
Does anyone know if there is a C# equivalent to python's "eval()" function?
yeah, I found those, and was hoping somebody here had some obscure knowledge of a unity function that does this
oh well
What are you trying to do, in terms of your game?
Awake is called before onenable, for each object individually. It's not guaranteed that every single awake is ran then every single onEnable is ran. Use Start
I want to make a scriptable object for a skill, where I can write the damage formula in the object.
I would just make a data c# script and hardcode your formulas
If you have all the numbers present in some sort of collection, then you probably could do this by parsing the string though itd really be a lot slower. You could even go as far as defining an operation which takes 2 numbers and does an operation on them, then have a list of these visible in inspector. The real tedious part is gonna be having a lookup from some index or ID to number.
Any option is really gonna be slow in comparison to just defining them all in code and using like an enum to choose which formula to use
you can do like semi parse stuff like building it like scratch using enums
Thx 😄 I think I might just think of it differently
Yep that makes sense
public void AddItem(int scriptableObjectIndex)
{
ItemData itemOwned = GetItemData(scriptableObjectIndex);
if (itemOwned != null)
{
itemOwned.ItemCount += 1;
}
else
{
CreateItemData(scriptableObjectIndex);
}
}
public void AddItem(ItemBaseSO itemBaseSO)
{
ItemData itemOwned = GetItemData(itemBaseSO);
if (itemOwned != null)
{
itemOwned.ItemCount += 1;
}
else
{
CreateItemData(itemBaseSO);
}
}
Can this be improved? It's repeated code, I am getting/creating data from either an index or a SO.
The order is basically:
Index -> SO
So if I have SO already, then I skip that part of getting SO by index, but everything else is the same.
The thing is that I want the ability to use both, so an item data can be added, removed, returned by either using Index or itemBaseSO.
I can probably just improve it by taking out if itemOwned != null into its own function, but thats about it.
Actually even that I cant do hmm, maybe a callback but that seems like an overkill 😛
but if you know the scriptable object index, why can't you give it the SO instance?
If you can just look up the SO itself from the index or other way around, then yes. Currently no
I'd improve it by deleting the int overload entirely, personally. Seems brittle
Yeah but if I remove int overload, then every script in the game has to get SO from database
Which is why I added it
ItemBaseSO itemBaseSO = GameDatabase.Instance.ItemList[itemData.ItemIndexSO];
well there ya go
!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.
public void AddItem(int scriptableObjectIndex)
{
ItemBaseSO itemBaseSO = GameDatabase.Instance.ItemList[itemData.ItemIndexSO];
AddItem(itemBaseSO);
}
public void AddItem(ItemBaseSO itemBaseSO)
{
ItemData itemOwned = GetItemData(itemBaseSO);
if (itemOwned != null)
{
itemOwned.ItemCount += 1;
}
else
{
CreateItemData(itemBaseSO);
}
}
but I agree, the index argument is flimsy
I give index to my SO
I'd recommend rephrasing the AddItem to AddItemFromIndex
I havent gone into guid route yet, its planned, but idk if it will happen for this game.
I will replace index with guid eventually
Some form of ID is fine if this is loaded from file for example. Otherwise I dont really see a case where you'd need to add an item from using a number
so the function will be AddItem(string itemGUID)
Since this way it prevents errors of using index and saving it as that can change.
But I need to make sure GUID stays unique forever, which is why I havent gone there yet as I have other things that needs to be done 😄
Its loaded with Resource.Load
I store it in a List and I access it directly from a list by index(not ideal I know, but at some point I hope to use GUID instead, we will see if time allows)
This is funny cuz I already did your solution for another script, tho in a different order:
public ItemData CreateItemData(int scriptableObjectIndex)
{
ItemData itemData = new ItemData();
itemData.ItemIndexSO = scriptableObjectIndex;
itemData.ItemCount = 1;
Items.Add(itemData);
return itemData;
}
internal ItemData CreateItemData(ItemBaseSO resultItem)
{
int itemSOIndex = GameDatabase.Instance.GetItemIndex(resultItem);
return CreateItemData(itemSOIndex);
}
Guess I need a break
your code scares me
so if this is how you plan to instantiate the ItemData, maybe create a constructor that takes ItemIndexSO and ItemCount as arguments for it?
in the console it keeps telling me that i need to assign a variable that i already assigned how do i fix this issue
heres my code
main camera is assigned in the inspector?
yeah
Probably what I should do.
And if that code scares you, then you'd have nightmare looking at other parts of it 🙂
screenshot of your inspector?
check for copy of this script
what do you mean?
you can go in hierarchy and type t:PlayerArms in search bar, there is a copy of this script somewhere
I'm following this 2D water tutorial that is just instantiating a bunch of circles each with their own rigidbodies and colliders. I like working with this simple method but the performance cost is kinda bad. I've heard of using DOTS but I want to check in with Unity discord before jumping into that. Would DOTS be the right move for this case?
For what procedural water? Like splashes? Deformation when jumping in it?
That does seem a bit extreme yeah. I personally made a bunch of transform points along the surface with a small circle collider then did the physics myself mostly
If something overlapped the point, find the velocity of that something and then displace the point and any surrounding points but gradually make the displacement smaller
I did some hacky velocity stuff that was a semi verlet integration sort of thing it's weird to explain
"physically accurate" water I assume. Such that it can spill and move around.
DOTS can make anything that requires many similar computations a lot faster, so yeah. A compute shader would be even faster, but you'd need to implement the particle physics in it yourself.
Hey there, in my top down game, I want a weapon pickup to show an info box besides it when the player walks over it/is in reach to pick it up, along with the keybind to pick it up (fortnite as reference). Now one of the problems comes when theres multiple pickups the player steps on. How could I handle that? I don't have any idea on how to approach this info box at all.
put a trigger that enables a UI object or use overlap of sorts
you could make it a WorldCanvas which would take care of easy positioning not worry about scale
depends how many you need on screen / look you can yse either like also ScreenToWorld forr regular UI
I only want one info box at a time
imo then the same worldcanvas that follows your player just for showing infos
I'm just wondering if I should make a singleton info box manager and OnTriggerEnter put the pickup on a queue or smth
and OnTriggerExit remove itself from the queue. Then the Manager could take only the first one in the queue to display, right?
yeah you can check in trigger what it is
wdym check in trigger?
oh just realized you are trying to handle the queue for multiple items
exactly, thats what confuses me 😅
its up to you , do you want it based on distance or your player's FOV / Dot
probably just distance
doesnt fortnite show only the info box when cursor is on the actual mesh of floor item
just want when the player stands ontop of a weapon item, it shows the info to pick it up.
Don't know how to handle that
ah sorry had it wrong in mind
eg
private void OnTriggerEnter(Collider other)
{
if(other.TryGetComponent(out IPickable pickupItem))
{
infobox.text = pickupItem.Name;
}
}```
thats an interesting approach, I'll think about that :)
You could also just use a Physics Overlap
which reiqures no rigidbody on trigger or item
do you have an idea how to handle when he stands ontop of multiple?
sort it by distance
i mean the player will have a rb anyways
store them in an array
this would be on a Trigger collider + object ideally not the same as player lol
uh okay, so add it to an array and sort it everytime one is added?
why not the player?
I would use OverlapSphere for example instead of OnTriggerEnter actually
oh yeah i can see that
thanks man, that was very helpful
i think i can do the rest on my own ^^
np goodluck there
sorry to ping you again, got some issues :')
How do I convert them from Collider2D[] to IPickable[]?
Do I sort them with some sorting algorithm or should I use Linq?
[SerializeField] private float pickupRange;
[SerializeField] private IPickable[] pickups;
void Update()
{
Collider2D[] cols = Physics2D.OverlapCircleAll(transform.position, pickupRange);
cols[1].TryGetComponent(IPickable, out IPickable pick);
}
IPickable was an example lol make your specific class, didn't mean you actually copy that exact class
also try get is a boolean it returns true if component is found and stores it in the variable pick for example
so a got a issue that i need fixing
yeah, but is there a way to directly get the Components/Classes from the array? I feel like GetComponent for each one in the list in update would be pretty extensive
is there a way to rotate a transform to have the same up as a ray cast normal without needing to manipulate euler rotation y?
well ideally you put them in specific layers so you're only browsing through the pickup items
Layermasks for the Overlap
alright, but the converting with a for loop is fine? I feel like there is a better alternative method that i just dont know about, but am probably wrong
if you going through multiple objects there is no other way to get around loops
they are not very expensive for a handful, unless you start doing crazy amounts of work with more than thousands of iterations
and even then.. checking for component is nothin
🗣️
Thanks ^^
not even sure what you're trying to do here 🤷♂️
out of my knowledge too
if you want to improve performance Iwould suggest learning the nonalloc version of Overlap
when you ray cast you can get a normal right, i want a transform to match that normal but without it affecting the y axis of the euler rotation
make a new euler and pass its own euler y as value ?
i've tried that and for some reason it decides to get wonky like it you changed the w axis in a quaternion
hmm can you show what you tried
ideally you dont want to mess with eulerAngles directly
you want eulerangles to quaternion
i've deleted basically all the rotation code i'm left with just this
var qerot = Quaternion.FromToRotation(TMP.transform.up, info.normal).eulerAngles;
var rot = new Vector3(qerot.x,qerot.y,qerot.z);
i don't know how to use the discord code thing to format sorry
ideally i'd like to chang rot.y to whatever id like
!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.
Does this make any sense?
pickups.OrderBy(x => Vector2.SqrMagnitude(x.transform.position - transform.position));
careful with LINQ methods and how often you use that
okay
I dont recall if Vector2.SqrMagnitude is better than v2.Distance or not
var qerot = Quaternion.FromToRotation(TMP.transform.up, info.normal).eulerAngles;
var rot = new Vector3(qerot.x,qerot.y,qerot.z);
sqrMagnitude doesn't square root the result like Distance does so it is a bit better
ahh ok
You could try it maybe running it betwen specific seconds instead of every frame , might improve some bit
in terms of sorting yes you need some compare method
how about I check how many are overlapping, and only if that changes I check/update the list?
do you need to sort them, or do you only need access to whichever is closest?
only the closest
var qerot = (Quaternion.FromToRotation(TMP.transform.up, info.normal) * TMP.transform.rotation).eulerAngles;
var rot = new Vector3(qerot.x,qerot.y,qerot.z);```
then just loop through the list a single time and look for the closest one, no need to use OrderBy or any other sort
ohhh right
i just want rot y to be whatever i want like placing a fan and still being able to modify rot y without it doing its own weird thing
was also thinking
Quaternion normalRotation = Quaternion.FromToRotation(Vector3.up, hitNormal);
float currentYRotation = objectToAlign.eulerAngles.y;
Vector3 newEulerAngles = normalRotation.eulerAngles;
newEulerAngles.y = currentYRotation;
objectToAlign.rotation = Quaternion.Euler(newEulerAngles);```
i'd have to test it
my head implodes with rotations sometimes
ill try it, i think ive done something very similar
uhm i still cant rotate the y to get what i want still
idk what that means , you need to show what is happening instead
do you mind vc?
with your solution (idk if i butchered the implementation) it does this
perfect
on walls perfect until
you rotate and it does it on the global y
oh Vector3.up is global
transform.up for local
if thats what you mean. I can't tell that much wha is going on vs whats supposed to look like
i cant screen record but it when its transform.up it spins around like crazy
rotate along the local y axis
like how this will rotate and the nob is always up and can spin
trying to have this part be placable anywhere and it faces up with the normal but i want to rotate along the local y axis aswell but it just doesnt want to
eh ill just preprocess every variable and with what i finish ill then apply that to the transform
how do you find the normal ? like in code
raycast?
yes
so the knob is supposed to always be at the top on each normal of the cube?
or world up
yes
like how in a camera controller you can face any direction without the z axis
i figured something out thanks for helping
raycast hitting itself?
if i want to find target direction its current position - target position right?
other way around
aw thanks
nope
unity is doing a unity
i really dont know how to fix this
i rotate the y axis in inspector
cool it turns left and right
i turn the z axis in inspector
COOL IT TURNS LEFT AND RIGHT
i turn x axis it rolls forwards and back
lemme record this on my phone i cant make this up
why is this happening
Can anyone be a dev for my game you have to: know how to make a map, know how to make a player model, and you also have to have experience
Congrats, you've unlocked a gimbal lock.
how do i not gimbal lock
Wait, nvm. It's not a gimbal lock.
Was that at runtime?
!collab 👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
yep
Then it must be your code messing with the rotation.
Wait, no. It is gimbal lock
Sorry
But it's probably related to your code.
Does the issue happen outside of play mode?
i disabled the script that cause that in that video
So can we consider the issue fixed?
i dont know
Well, it sounded like the issue is was with the script and after you disabled it, it was gone..?
I'm not sure how else to interpret your previous message
im just trying to find a way to align to a surface normal while still being able to rotate the along the up vector
Well, you did seem to be able to rotate around the up vector in the video🤔
Around world up
Which is the transforms up? I don't see the transform gizmo in the video
the little knob is a indicator sorry for not showing
So when you disable the script, it works?
is there a way to vc?
not in this server. though really, if you have a script which is affecting the rotation then maybe you should point that out instead of just saying the z axis isnt working.
If you need help with specific code then you should just ask about that, and look at the #854851968446365696 on how to ask
i have asked and showed the code
cs
Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);
Vector3 rot = normRot.eulerAngles;
rot.y = rotation;
//
TMP.transform.eulerAngles = rot;
Anyone here has experience with ML Agents? Doing an enviroment where an agent needs to click a button, after the press of the button a platform with food on top will spawn. Agent needs to jump to the platform and collect the food. He learns quite quickly how to press the button but can't for anything I tried to jump to the platform. Can anyone help me? Tried multiple types of observations, using ray sensors, mixing both, nothing works. He spams jump on the edge of the innitial platform and doesn't jump to the desired platfom.
You would use Quaternion.LookRotation(a, b) where:
ais a vector tangential to the surfacebis the surface normal
ah i scrolled up further, it seemed like the question started from the video. Though what do you mean you want to align to a surface normal and rotate around transform.up? Like which part of the object should align with the normal?
rotating it from inspector definitely will not follow this rule, and your code will constantly be fighting to set it based on this code.
me head am hurt
the base of object aligns with the normal it attaches to, and i have a float variable for rotation and when i press r that float goes up by 45, i want to rotate the transform by its up vector by that rotation variable
the funny remote is rotated to face the up of the surface (left of it), i want to rotate the romote around while keeping it attached to the surface
the surface can be facing any way so i want to rotate it regardless if the up vectors direction but follow along it
this is it with this code to direction it
Quaternion normRot = Quaternion.FromToRotation(TMP.transform.up, info.normal);
this is it with the same thing but using world uo vector
Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);
been trying to find a fix for the last 3 hours
if (Input.GetKeyDown(KeyCode.R))
{
rotation += 45;
}
//
TMP.transform.position = info.point;
TMP.transform.Translate(-PlacingPart.PivotPoint.localPosition);
//
Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);
Vector3 rot = normRot.eulerAngles;
rot.y = rotation;
//
TMP.transform.eulerAngles = rot;
this is the code
the position part works perfectly fine, its the rotation that doesnt want to behave
info being a raycast variable
rot.y is rotation around the y axis. Are you sure that's what you want? Considering that you're applying rotation from world up to surface up to it.
i dont want the world up to rotate i want the transform up to
this happens when i use transform.up
You're not listening
no
no thats not what i want
i want it to rotate on the transform up without it glitching around
Can't you just do transform.up = hit.normal?
what does that do exactly
allows you to specify up and prevents gimbal
really?? :0 thank youu
It would also help if you don't record your screen from your phone but use a dedicated software for screen recording. It's really hard to look at...
i dont have any
Download one
Obs studio for example
This part of the server(and dev communities in general) etiquette. It's not very nice to share photos/videos of your screen from your phone.
Make it easier for people to help you and you'll get better/more help
eh it didnt work ima give up, sorry for bothering you
you seem to have a raycast/normal problem in your video so I would fix that first
how so?
your cursor is bringing the mesh into the other meshes before rotation
assuming you're not childing the object or anything, it seems you just need to use world up axis and rotate it on the y
so start debugging values and make sure your cursor isn't interfering with it
i wanna have a debug screen where I can keep track of how many poco objects exist, just to make sure they're actually getting destroyed at some point. Is this a good usecase for WeakReference? Ive never really used it before and this was something I saw popup online a bit when researching.
Im thinking of something like this https://gdl.space/jilujumuno.cs
Otherwise im just trying to use the memory profiler or the finalizer to check if my instances are being destroyed, which isnt fun
dub
i need help my build and run is diffrent from my editior and i think its related to a tag problem
ill send a screenshot of my script
make sure to also check the player !logs after you test a build, you may have errors in a build that you are not experiencing in the editor
there are zero errors
have you confirmed that by reading the log file?
that doesn't mean your build is not experiencing runtime exceptions. if only there were some way you could confirm whether that is the case or not
you'll need to show the relevant !code for that
📃 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.
and you still need to make sure that the build does not have errors logged in the log file
im new to unity so how would i go about doing that
because, naturally, an error would cause issues with your code like exactly what you've described
remember how that was literally the first thing i told you to do #archived-code-general message
i thought you meant in the console, i didnt know that there was a seperate file sorry.
i specifically told you to check the log file
where is the log file typically
did you not even bother reading the bot message that i just linked back to?
there's a convenient "Documentation" link that tells you where all of the log files are located
ok, thanks
do you know why this is happening?
one of your prefabs might be included in a scene but is deleted
or your script is deleted but still applied to a gameobject
it says object not set to an isntance of an object in the debug files
but i cant open log since it locks my cursor
this is my file
hi is there a way to automate adding textures to material?
i have a lot of materials that i need to add adding one by one is quite tedious
look at the errors, it gives you the file and line number that they occur on. so show those files
thank you my glorious king
if this is something you want to do at edit time, then you can easily just write an editor script that references the materials and textures and applies them. check the documentation pinned in #↕️┃editor-extensions to learn how to write tools for the editor
one of the most important things you'll probably need to do is to ensure you mark the materials as dirty when you modify them (i assume, i'm not actually 100% sure if that would be necessary but it usually is when modifying assets via editor tools)
So, I can’t really do SQL locally on my machine, and would like to apply databases with a test environment on my game, any suggestions?
SQLite?
why can you not do SQL locally? Which RDBM systems have you looked at?
Sql server just makes my pc lag and keeps running and I end up reformatting each time
Would anyone know how to get the colliders to behave like they do in getting over it? where despite being in 3d,space the colliders behave as if they were 2d from the cameras POV.
Pretty sure MS Azure has a free tier which you can use for SQL*Server
I’ll look into it, I tried using azure a couple years back for practice and it was really costly
Also MySQL is not as heavy on resources as SQL*Server
I’ll look into that as well
there is also (shameless plug) https://assetstore.unity.com/packages/tools/utilities/sql-for-unity-database-115308
Same way as in a 2d dame
This would be a great tool to fit into production, but at my current stage, I want to make sure I get the fundamentals and practices right first, bookmarking it for sure
You should not consider this a 3d game but rather 2d. So you use 2d colliders everywhere.
Ill try it.
Otherwise you have a 3rd axis that is never used anyway
Because a 2d game also uses 3d objects. It's just all flat. Here it does actually occupy a third axis but that doesn't mean you need to apply this to the colliders
Its so odd to apply a 2d collider to a 3d object but here goes.
hmm i tried but none of the colliders automatically adhere to the geometry. Im trying to get like a mesh collider, but for 2d
Like getting over it, I need the collision to be really accurate to what you see.
Again, even 2d objects are 3d, so there really isn't a difference
You just need to make sure the collider remains the correct orientation
Hey. Does anyone have any ideas on simplifying this Coroutine ? The methods used are irrelevant.
can you just delete the first 5 lines of it?
No
Presumably delay and interval are not the same.
That's right
And that's the reason
Also instead of:
while (true)
{
if (!CanMove(value))
yield break;```
why not just:
```cs
while (CanMove(value))```
Haven't mentioned it, you're right
Now it should be the finished version
Thank you!
I just felt like I was missing something.
I mean you could do something like:
WaitForSeconds interval = null;
while (CanMove(value))
{
Move(value);
yield return interval ?? new WaitForSeconds(_moveDelay);
interval ??= new(_moveInterval);
}
The code is shorter, but is it better? I'm not sure.
This looks confusing at first, but I think it's much better. Thank you!
Also the first WaitForSeconds after the ?? can be simplified too
well you do lose the GC optimization
Not much
If your goal is "fewest number of lines" it's good
Wdym by GC optimization?
This version should only allocate 2 waits, just like the original.
Reuse of this:
WaitForSeconds intervalWFS = new(_moveInterval);```
oh
you're right
sorry it's early
Sounds like coffee time 😄
But yeah if you didn't need to care about allocations, eg if you are using UniTask, it'd be so much simpler to write and understand:
var hasDelayed = false;
while (CanMove(value))
{
Move(value);
await UniTask.Delay(hasDelayed ? _moveInterval : _moveDelay);
hasDelayed = true;
}
I have a code that sends some text to my "custom arduino controller" over serial and my arduino replies to that with 2 lines of text but somehow I can only get unity to interact with one of the lines of code (even if I disable the first line it won't interact with that second line) so I feel like it has something to do with the formatting. How can I get it to also interact with the second line?
It only replies "DitIsEenTest" while I'd also expect "Goedemorgen" (The arduino does send both)
Already simplified both codes as far as I can to exclude other errors, but I'm still a modeller and not a programmer 😅
Unity: https://hatebin.com/tgjhrcqcmi
Arduino: https://hatebin.com/icswfhrwql
(I almost feel like an async/await or UniTask salesman at this point, but truly almost every question regarding coroutines it's almost always nicer to write using those instead)
this deosn't work
if (receivedText == "TEST") {
Serial.println("Goedemorgen")
but above does?
correct
are you able to print Serial.println(receivedText)
make sure "TEST" is what is actually being received
Not sure how I would do that, can only connect to the arduino with 1 program over serial so if I'm connected with unity I can't connect to it with other software afaik.
just print your receivedText instead of the if statement
oh that was already in it that was correct
can you print if receivedText equals "TEST"?
oh wait, the println is on arduino site.
yes the aurdino code , i was saying if they can print on display what is actually being received instead of generic logs
changed it to display what is being received and it is "TEST"
sorry been a long day and thought I changed it back to that before asking the question 😅
try
if (receivedText.subString(0,4) == "TEST")
also very unsure how the loop is actually looping
For me it looks like you are always writing two lines in one serial write.
Thats why you always get the same result in the first line?
So I am wondering, why you readline instead of reading all
I commented out the first lines when I tried that, will try reading all when I'm home. Didn't know that's an option.
:(
not a code question. also dont crosspost
posting the same question in multiple channels
👍
I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.
How can I find out the inverse lerp of Vector2? That is:
IF:
// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)
And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);
To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true
N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
Hi guys, I want to show a dialog box when the app reopens, my code is as follows, but when I click the button in the dialog box, it reopens my previous window. I think it's the cause of some system calls, but I can't find the information about it, can anyone help me
i'm pretty sure a popup causes the editor window to lose focus so yeah this would be called after closing a popup 😅
do you plan on having this in a build?
this class is editor only
This is just a demo, this issue appeared in my toolchain (Something convenient for me to test), and I found the reason because of this, so I extracted them
alr just letting you know, wont be able to build with those classes
Is there any solution? I solved this by setting a trigger to get my function running on the next frame, I don't think it's very elegant
oh oh, i get it ,thx
i don't think there's a particularly elegant solution, but it's editor only code anyway so as long as it works it doesn't matter too much 😄
with all you mean "ReadExisting()"? That also doesn't change anything.
Doesn't && false mean this will never run?
I'm sorry I misled you, this false is added later and doesn't have any effect on my question
It's just because I can't pause my Unity program
I get it, thx
Hi simonp, the phenomenally speaking, that is, the focus reacquisition is after OnApplicationPause and OnApplicationFocus(Maybe it's getting focus at the OS level), is this conclusion correct? My search ability is very poor, Is there any material related to this?
The first one doesn't solve the problem(OnApplicationFocus runs after OnApplicationPause), the second one can
hello there, I have a Texture2D of the terrain heightMap and I will convert to a flatness map by using the delta rgb with the neighbors to get how flat the pixel is. My question is with my flatness Texture2D, how can I find the biggest area within a specified delta?
to sum up, with a texture like this how can I localize the whites spots?
i am trying to make a top down shooter and I want my enemies to spawn randomly, problem is that the enemies can spawn right next to the player and damage him instantly, is there s simple way to fix this?
get the player position and the possible spawn point. Calculate the distance between these and if dist < min radius, doesn't spawn
I need some advice setting up an if for my idle animations
It's set up currently so it can only activate while player is grounded and is not moving but issue with that setup is that if the player is only moving left to right or forward to backward there's a few seconds where the conditions are all met and plays the idle for a few frames between changing run directions when it shouldn't.
I tried solving this by making a coroutine which stores the current value of the player's inputs and then waits a few seconds to see if both variables still equal each other but then that leads to the issue of the run animation taking longer to end than it should.
Any recommendations/suggestions on something better I could try to fix it?
how do i get the possible spawn position? I am using an instantiate function
How do you spawn randomly? You generate a random position and then instanciate the obj to the postion?
I get a random pos from the left side of my screen to the right for X and up and down for Y, and then I instantiate the enemy somewhere inbetween
I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.
How can I find out the inverse lerp of Vector2? That is:
IF:
// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)
And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);
To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true
N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
Yes, how do you get a postion somewhere inbetween, what is the postion input of your instantiate method?
I use a Random.Range from the left side of my screen to the right side of my screen to get an X value that spawns my enemy inside of my view and same for Y
it basically creates a rectangle around my camera where an enemy can spawn
Here’s the Lerp equation:
(b - a) * t + a = value
Re-arranging it gives
(value - a) / (b - a) = t.
To convert it for a vector2, you would just do one inverse lerp on the x values, and one inverse lerp on the y values
Edit: I just noticed that you are solving for the T value which is shared by both. You should be able to just solve for it using either x or y.
Then do it outside, store the value and put a if( Vector2.distance( posTmp, playerPos) > minRadius) {instantiate,,,,} else {find another pos}
I use a float to store the randomX value, so i cant use it in the vector2.distance, can I convert the float to a position?
new Vector2(posX, posY)?
can I call the function again to retry the Instantiate if its too close to the player with something like a return void?
if you need the gameobject as input, return null if failed and if you method is null, retry again. If you don't need the gameObj as out, just out a bool.
what does the gray message mean?
can you show the whole method or what you are trying to do
yes
for void you just do 'return'
your method is a void
okay
what are you trying to do
holy moly it just spawned like 50 enemies
You got wrong
spawn an enemy every 2 seconds at a random position, but not too close to the player
Take the transform + new Vector... ) and put it in a new vector3 before the instantiate
then take instantiate and put inside the if
make your Spawn as bool Spawn
retrun true inside the if and add else retrun false
in you Update loop, reset the timer only if Spawn == true ' if(Spawn()) '
And Is your game 2D or 3D?
then this will work. Try to write it and copy paste your code in the chat. I will help if it doesn't work modify.
I am confused but Ill try my best
do you mean something like this?
Wait few seconds, I will write the code in the chat
okay
https://www.desmos.com/calculator/kowaqfrcpk
@unique trench Here’s a Desmos example. You can drag around the points. As you can see, you should be able to use either X or Y, as long as the both points aren’t on the X or Y axis. Otherwise one of them will be undefined from dividing by zero
nah i tried everything
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class Shield : MonoBehaviour
{
float timer = 2;
Vector3 playerPos = Vector3.zero;
float minRadius = 10;
GameObject enemy;
private void Update()
{
timer -= Time.fixedDeltaTime;
if (timer < 0)
{
if (Spawn())
{
timer = 2;
}
}
}
bool Spawn()
{
Vector3 posTmp = new Vector3(Random.Range(-15f, 15f), Random.Range(-7f, 7f), 0);
if (Vector2.Distance(posTmp, playerPos) > minRadius)
{
Instantiate(enemy, posTmp, Quaternion.identity);
return true;
} else
{
return false;
}
}
}```
this
just disable the script like it was suggested, inside the same if statement
thanks
Just put a Static bool isGameOver and in your movement code put if(!scriptName.isGameOver) or time scale = 0;
no need
why not?
throwing a static variable at this problem is unecessary
if health is 0 script can just disable itself
Do you want to pause everything or just stop spawning more enemies?
I think op was trying to only disable movement of player when dead
but i i have a walksound and i wanna make it also turns it off
where in the code are you playing the sound?
you could use an event from a game manager or something, this way other scripts can do something
📃 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.
don't use screenshots for code
your vscode still doesn't seem configured for unity btw
did you get the Unity Extension?
yes
well sounds like you missed the other steps then
alr would advice you make sure that is https://code.visualstudio.com/docs/other/unity
it will help you in the long run
anyway In regardss to this, a simple solution is just learning the event
This is another little Unity engine tutorial about how to use animation events! They can be used for all kinds of things, but in this video I show how to use animation events to sync up an effect (a particle effect or a sound, maybe) with a character's footsteps. You can use this to create little puffs of dust, or a stepping sound, or even somet...
a bool would working but imo polling it everyframe to be checking inside every script is iffy
this could also work sure for individual footstep and use OneShot instead , this should solve the issue of having to Call SetWalking(false) on gameover
I meant this event https://learn.unity.com/tutorial/events-uh
Good to know, never used this.
I'm having a rather annoying error pop up for my procedural generation. I'm trying to have a GameObject variable copy the "prefab" in this script but I get the mildly infuriating "Transform resides in a Prefab asset and cannot be set to prevent data corruption". not sure how to post code correctly tho
very good to learn and writing more modular code
if you want an inspector solution there is also UnityEvent
lets you link multiple scripts and methods inside inspector, same way OnClick basically works for UI Button
I see, I should use this in the future Thx.
!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.
Hello, I am currently attempting to make a procedural voxel terrain in unity and using the async and await keywords to multithread the process, except I get a MissingReferenceException after I stop playing the game in the editor for some reason. Any ideas as to why it would be the case?
Here's the code and the line I get the exception at is commented below.
private async void GenerateMeshForChunk(int i, int j, float[,] noiseMap)
{
var result = await Task.Run(() =>
{
MeshData meshData = new MeshData();
for (int y = 0; y < chunk_height; y++)
{
for (int z = 0; z < chunk_size; z++)
{
for (int x = 0; x < chunk_size; x++)
{
//Debug.Log(new Vector3Int(x + i * chunk_size, y, z + j * chunk_size));
List<Vector3> faceVertices = GetCubeVisibleFaces(new Vector3Int(x, y, z), new Vector3Int(i * chunk_size, 0, j * chunk_size), ref noiseMap);
for (int k = 0; k < faceVertices.Count; k++)
{
meshData.vertices.Add(faceVertices[k]);
}
}
}
}
for (int k = 0; k < meshData.vertices.Count; k++)
{
meshData.indices.Add(k);
}
return meshData;
});
chunks[i * num_chunks + j].transform.position = new Vector3((i * chunk_size), 0.0f, (j * chunk_size)); //I GET THE ERROR ON THIS LINE!
chunkFilters[i * num_chunks + j].mesh.Clear();
chunkFilters[i * num_chunks + j].mesh.vertices = result.vertices.ToArray();
chunkFilters[i * num_chunks + j].mesh.triangles = result.indices.ToArray();
chunkFilters[i * num_chunks + j].mesh.RecalculateNormals();
}
Can you paste the error?
Do you destroy your chunk at some point?
no, I just stop the game and I get that error after stopping it for some reason.
Because its async and async doesnt align with unitys play mode
stopping playmode will destroy all the gameobjects
oh? so I ignore it?
No, this means your code is still running after play mode
You need either to rethink about using async or use like a cancellation token
oh... is there a way I can stop the async after I stop playing?
Oh, I didn't see async. Never used it, what is async for?
multithreading
syntax sugar for not writing a state machine that handles non-blocking operation
is there a way I can stop it after I stop playing?
You need either to rethink about using async or use like a cancellation token by bawsi
what is a cancellation token?
God Damn, this is useful. Glad to know this exist now.
I see the same error in a async tutorail: https://gamedevbeginner.com/async-in-unity/
A way to stop the function from running past play mode, you'll definitely find solutions for this online
Read this tutorial
thank you!
thank you!
Well you really dont wanna use it if you dont know what you're doing. Mostly it's not needed
Though I find it odd you're suggesting tutorials on it when you just learned what async is...
Theres no way you read through all of that
I just read realllly fast, Jk, I saw the same errors as he asked about before. That's why I posted this tutorial.
Can also use UniTask, I think UniTask handles the editor play mode cancellation for you.
I have my own question: I have a 2D texture like this one. What would be the best way to find the middle of the biggest area?
Doesn't need to be with Texture2D, I have the same data in a float matrix
I think you can do some version of heuristic matching. Perhaps fill the white pixels with two values, distance from black and number of whites surrounding the pixel.
or just smudge or blur the texture, the whitest area in the end is the winner?
I see, Good ideas. I try it now. Thx
good luck
blurring should work as long as the kernel size is right but now the problem becomes how to get the correct kernel size
i have this that was procedurally generated. How do i get rid of the bar-code look on certain parts of it?
I also want to make it look a bit mor natural, any suggestions?
nvm i got it it was the model scale
I have a player, snake, which consists of the blocks, which all have a BoxCollider2D on them. The snake's length can be changed, which means it can have a large amount of blocks. Moving a snake around translates the 1st block on 1 unit to the desired direction, and the other blocks' positions are assigned to their previous one. Every block is 1x1 in Unity coordinates, and its position should always stay inted at the end of the "continuous" movement.
What would be the best way to apply the gravity to the snake to not decrease the performance too much? Using the Rigidbody2D with the CompositeCollider2D doesn't work as desired, as the collisions with the ground blocks aren't calculated precisely and the blocks' positions aren't inted after the application of the gravity.
I would probably not be using physics for a Snake game at all
unless you're doing some physics-based twist on it
Right, that's what I thought too. I wanted to use a while to create a loop for every single block and check whether it has a ground block 1, 2, 3 etc. units under it. It works perfectly when the distance between the ground and the number of blocks aren't too big, but once they get, the performance is going to decrease significantly.
Perhaps, there is any efficient method, which allows to check for the nearest Collider2D under the CompositeCollider2D.
But it's also so that the distance between the snake's block and the ground block should be considered.
Even when the 2nd block is under the 10th block, the smallest distance between the block and the ground block should be chosen
So I feel like creating a Raycast to the bottom for every block with the smallest y position in its column to check for the distance to the first Collider2D should be the best option.
It's also important to break the process when the Collider at the distance 1 is found, as this is when the snake is staying on the ground
And every block's collider should cover the entire 1x1 space
I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.
How can I find out the inverse lerp of Vector2? That is:
IF:
// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)
And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);
To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true
N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
How about this?
private static float InverseLerp2(Vector2 a, Vector2 b, Vector2 n) {
var ab = b - a;
var av = n - a;
return Vector2.Dot(av, ab) / Vector2.Dot(ab, ab);
}
N = A + pct * (B - A);
pct = (N - A) / (B - A);
Proof:
N = A + pct * (B - A) = A + (N - A) / (B - A) * (B - A) = A + N - A = N;
Why can I not cast an object type as a int to a function that takes a int param? Why do I need to first cast it to a float?
public void SomeNetworkFunc(object[] data)
{
SomeLocalFunc((int)((float)data[1])); //works without issues at runtime
//instead of simply...
SomeLocalFunc((int)data[1])); //causes "cast is not valid" at runtime
}
public void SomeLocalFunc(int value) { ... }
If its an object, shouldnt I be able to cast data to a int? Even as a float, shouldnt data be able to be cast to an int without the double-cast? Is there maybe a better way I could handle this to not need the double cast? (nothing wrong performance wise in my game with it and its not called very often on the network, I just think it looks ugly and seems like a extra step forced on by my approach maybe)
object[] data = new object[10];
int i = 0;
int? x = data[i] as int?;
the reason you can do object -> float is that float has NAN for invalid values int does not have that
so using int? will get around that
Ah interesting, thanks for explaining that, I dont think ive ever used ? on a variable type, ill try it out
true, false, file not found
interesting -- I didn't know float could produce NaN for an invalid cast
hey guys! quick question. what would be the most efficient method of spawning objects in a procedural terrain generator?
I saw something about how structs don't get collected properly in the editor and so when playing in the editor the struct's data won't "reset" until the scene is fully reloaded. Is that true or am I mixing it up with another thingg
It's really unclear what you're talking about with "collection" and "resetting"
Or what that has to do with structs
idk I just glimpsed at the convo but something about how if you change the data in play mode it will stay like that even when you stop playing, which isn't the usual behaviour. I may be confusing it with scriptableobjects though I'm really not sure
Is there another way to spawn objects besides Instantiating them?
there probably is but not sure about that way then. have heard from some places that Instantiating is resource heavy while others say it not so i'm not too sure
You'd have to be comparing it with something to make a statement like that
there definitely isn't another way
mm, got it. so Instantiating with static batching is an effective way to spawn things?
oh, unless you include new GameObject(), of course
I mean if you want GameObjects, there's not much choice
If you're willing to step outside GameObjects you can do other things
can you build Windows IL2CPP on Linux? if not i have to reload in Windows. I despise windows.
You definitely are confusing it with scriptable objects
Any resources for a SFX singleton manager? One feature I've yet to really touch in my projects
Am I looking at pooling audio clips or is it like a single component with callbacks
https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
Like how performant is this thing?
i imagine that pooling would be more performant than that. i haven't really done much testing with that myself but i did make an audio source pool that basically does that. It's just a singleton with an object pool that will enable an AudioSource object, move it to the point I tell it to play at, then start playing the sound and returns it to the pool when it is done
oh man do I love object pooling
does anyone have a good script for an android flycam or freecam? I just want to move around with touch controls.
#🤖┃ai-navigation message sorry for the bump but could anyone help with this ai navigation problem
don't crosspost
Does anyone know why my shader render only in my left eye on the vr?
!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.
so im confused by trying to combine two loops
i have a level preview that is supposed to populate each button with one level. all it does is change the sprite and the text for now.
but i cannot get it to work. it always takes the last entry of the levels (in this case level 3).
what should happen is ofc, that the first button is level 1, the second button level 2 and so on.
here is the code thats driving me nuts:
//runs through each buttons
foreach (var button in buttonImageText)
{
//checks if sprite was overwritten
if(button.Key.overrideSprite == true){return;}
button.Value.text = "Empty";
//runns through each level
foreach (var level in levelSpriteList)
{
//SHOULD: checks if the button sprite is equal to a level sprite
if(button.Key.name != level.name)
{
button.Key.overrideSprite = level;
Debug.Log("amount of sprite calls");
}
else
{ button.Key.overrideSprite = null;}
//SHOULD: checks if button text already has level name
if (button.Value.text == level.name) { return; }
if (button.Value.text != level.name)
{
button.Value.text = level.name;
Debug.Log("amount of text calls");
}
}
Anyone ever implemented EAC to their game?
button.value.text starts as Empty. It will never be == level.name and so will always contain the name of the last level
but if button.value.text is not equals to level.name it should set it to it?
which it does. Look.
text = Empty
loop
is Empty = level1 ? - No, text == level1
loop
is level1 == level2? No, text = level2
loop
is level2 == level3? No, text = level3
end loop
yeah but then i guess my question is.. how do i make it so it sets the correct name for each button only once
totally rethink your logic and learn to read code
Hey, whats more performant, vector3.distance vs sqrMagnitute? I'm using it to check if I should execute logic based on if an object is not close enough to its default position.
private void Update()
{
float sqrDistance = (slideHandle.transform.localPosition - slideHandle.ForwardPosition).sqrMagnitude;
if (sqrDistance > positionTolerance * positionTolerance)
{
Debug.Log("executing");
}
thats not helpful
to start with you dont need 2 loops. Only one on level and try it from there
and use a for loop not foreach
i already did try that, but i need to get a ref on each button somehow
yes, use the indexer from the for to get the button corrsponding to the level
can anyone help me to write code for my UI design I don't know too much about script but I write it for my collage project
Nobody is going to do your homework for you. You can !learn how to use Unity.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have code and logic I need decimation link for structure assign I lacking in sytax
What does that even mean?
what do you think the link to unity Learn is?
yeah but I can find I my English as you see not good
there is aslo https://dotnet.microsoft.com/en-us/learn/csharp. which is available in many languages
oh thanks
Haven't tested it myself so I could be wrong but I always use vector3.distance for simplicity purposes as that's the whole purpose of the function
How do I stop the camera moving like that?
ok that's good to know then, glad I'm not completely crazy lol
mathematically speaking both are probably so few lines of code that neither are very impactful unless we're talking in the scale of hundreds if not hundreds of thousands of calculations a second (which will probably be slow for other reasons)
can someone help me with this??
not really, we'll need to see where the camera is in the hierarchy and possibly the camera controller code too
the way it's animated could be causing it
the code is https://paste.ofcode.org/aijKstjpWt62YzQuTrzWWv
so one small thing is that iirc you don't multiply mouse movement by deltatime
but that's not causing the issue that's just something to know
otherwise code looks fairly sensible so I'm going to assume it's probably something to do with the animator
if I'm misunderstanding what the issue is though, it could well be input handling or the deltatime thing
stop moving from left to right with the walk animation?
Do you want to stop the left to right movement when you character is moving?
yh
how do I stop it?
2 way: 1- remove camera from the spine and put directly on Ch15_nonPBR with the height offset. 2- make a script to restrict camera rotation.
what about the camera root?
that's the no.1 option
Change the camera parent
how do I change the height offset to 2
just drag and drop the camera under Ch15_nonPBR. The offset would be the Y component of the transform position.
I'm on linux (EndeavourOS, X11, KDE, everything up to date)
I have done every step on https://code.visualstudio.com/docs/other/unity, including ensuring the Visual Studio package is up to date
But I still do not have code completion, neither for my own classes, nor for unity stuff. What could be the issue?
Just to double check, you are using the Visual Studio Editor package right? The Visual Studio Code Editor package is not the right one and will not work.
yes, that's the one I'm using
@light surge would this script to restrict camera rotation work? https://paste.ofcode.org/nKCa59cuLZ7pz5neCVBrB7
Try regenerating the project and solution files.
already tried just clicking the regenerate thing, although I'm currently deleting it all myself and restarting everything
nothing changed, however when vscode is starting up, it does highlight all keywords properly for a second, then everything goes to trash
You can try to clamp the Y axis to a small angle with this code. May work.
how can I clamp the Y axis?
Run the command "Output: Show Output Channels..." and check channels of .NET Install Tool, C#, C# Dev Kit, Unity, and Projects. See if there's anything wrong in the output.
float clampedXAngle = ClampAngle(currentRotation.y, minAngle, maxAngle);
// Apply the clamped pitch angle
currentRotation.y = clampedXAngle;
// Update the camera rotation
cameraTransform.localEulerAngles = currentRotation;```
this
should I put the script in the camera inspector?
C# Dev Kit has this suspicious line:
Failed to listen to project initialization status: Error: Activating the "Microsoft.VisualStudio.ProjectSystem.ProjectInitializationStatusService (0.1)" service failed.
You can, just be careful between this and the camera mouvement.
I've never seen that before, but that's probably a good starting point to search.
it didn't do anything?
seems like a dotnet issue, and reinstall has helped others
I haven't dealt with this in a long while, I don't have time to solve this problem now... ffs
take the Ch15_nonPBR world Y.angle and feed it to the word Yrotaion of the camra
in this
what Ch15_nonPBR world?
add few lines that get the ch15_ononPBR Yrotatation in euleur angle and put it in the world Y rotation of the camera.
its 0
I know, but you need to do this everyframe, do it with c# code and the rotation you see is local rotation.
is this correct? https://paste.ofcode.org/3HxWnYBvwnk5zeA5EX5aqn
add this code at last of code in CamMovements(): csharp camera.transform.rotation.eulerAngle = new Vector3(camera.transform.rotation.eulerAngle.x , RootGameObject.transform.rotation.eulerAngle.y , camera.transform.rotation.eulerAngle.z);
this code wont work, change your main code as I wrote above
RootGameObject is a input and is Ch15...
is this all I need then I shouldn't use the one i sent you ?
I think
Is this correct? https://paste.ofcode.org/7PbkvvHxtwdEqaDfsPtri6
look fine, try it.
didn't work
is the rotation still here?
what rotation? btw the camera is still moving side to side when moving
this is soo dumb how the hell do I fix this. I followed a youtube tutorial and the guy didn't have the same problems as me. I literally copied what ever he did
Make a empty Gameobj as parent of your player model and put the code there. Then put the camera as child of this gameobj.
Didn't work if I remove the camera root and the code along with it will it be fixed?
hello, i am trying to use unity AR functions but I cannot figure out how to grab the texture of an ARTrackedImage
I found this
Texture2D referenceTexture = trackedImage.referenceImage.texture;
from Unity Doc but it doesnt seem to work though since the it's null
I know i am tracking an image because if i do this:
{
Debug.Log("Tracking image: " + trackedImage.referenceImage.name);
}```
it prints out the image's ref name
any clue?
Does anyone have experience with MessagePack?
I've been trying to get it working for hours on end...
Now the issue is that the GeneratedResolver.cs can't find my SavedObject and StructureData structs
I still don't get it, nor can I find them manually, they aren't in a namespace per se
MessagePackCompiler's generated code is trying to reference them via global::SavedObject and stuff...
Can Vector2.normalized ever return 0,0?
no because if normalized it must have a magnitude of 1
I believe it returns a zero-vector if you give it a zero-vector
indeed
(it's the same for both the property and the function https://docs.unity3d.com/ScriptReference/Vector2.Normalize.html )
being pedantic, it's not 'returning 0,0 it's returning an invalid input
I've experimented with the issue and figured that I simply have no. access. whatsoever. to any of my scripts or namespaces from that file, I don't understand how this could be
it explicitly returns a zero vector if the input is too small to normalize
i am not sure if that includes very very short vectors, or if it only includes the zero vector
//
// Summary:
// Makes this vector have a magnitude of 1.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Normalize()
{
float num = magnitude;
if (num > 1E-05f)
{
this /= num;
}
else
{
this = zero;
}
}
it should normalize magnitude < 1
It seems to be essentially isolated from the rest of my project or something, any idea how this could happen?
well, there's my question answered!
Where did the generated code wind up?
Unity needs to see it so that it can create a .csproj file (or add information to an existing .csproj file)
who else hates async programming
Unfortunately, the world is async 😄
Async is great, it's just that Unity never used it so there's not many places where it's available
Do not post the same question in multiple channels. Delete from here and stay in #💻┃code-beginner
Well, you have to try. I'm pretty sure that's a problem with you child/parent structure. Gl
UNREALTED to my previous message:
Question: I'm using render Textures to create my impostors. Is it the right way or it's wrong ? Just to be sure before I do every angle (Sphere).
Don't need to say to add Fade between angles. I will.
what's an imposter
oh is that some sprites with different frames
id' just use the sprite/texture atlas
From a article: An Impostor
Impostors is a technique used for a background of the game environment to fake 3D objects by using its texture maps and transfer them onto images or billboards.
This way, the number of polygons is much fewer which leads to spending less time to render a scene but the quality of the environment remains almost the same. The key point of this technique is to replace those 3D objects that aren’t in the main focus of the player’s view so he won’t spot the difference.
To sum up, It's a way to fake a 3D gameobject with a 2D sprite. The cherry tree on the far right is 3D. The two in middle are 2D.
no clue the overhead of using multiple cameras like that even if you're just capturing a single render, so something to profile. Otherwise cache yourself the textures and stick em in some dict with texture coordinates imo
hi im trying to learn how to have items in my enviroment with scriptable objects attached to store the items data. i have got the scriptable object file working but struggling to add the data to a game object that my player can pick up. anyone able to direct me to some resources that can explain how to do this.
create a script which declares the SO class type , attach that script to the gameobject and set to so asset in the inspector
Once you made the class, you'll be able to create instances of it as files, by right-clicking the Assets window and selecting the menu item you've set up in the class. Then once you have them, you can create a public or serialized field in one of your scripts and drag-drop the ScriptableObject instance.
ok so done that but its not loading the prefab for the item into the scene. im guessing im missing something else
i have loaded it onto a empty object. should i be adding it to a prefab of the game object even though the SO has a gameobject field?
what im trying to do is have items that can be picked up and scrapped so i am trying to use SO to hold the data on the materials for the item
you should have some thing like
Project
SO Script
-- SO Asset
MB Script
-- Field of same type as SO script
Hierarchy
GameObject
-- Instance of MB script
-- Reference to SO Asset
yea dont have anything like that i have a prefabs folder for the stuff i made in blender to learn this stuff and a scripts folder for the SO and other scripts
what does MB stand for ?
Monobehaviour
ok
The GameObject can also be a prefab in the project
right but in my SO i have set a public GameOject field to set the prefab to but the prefab is not being displayed on the empty game object
you are going to have to show your inspectors of the objects
am i right in thinking i just need to setup the object with the SO then make a prefab of that game object in the Hierarchy to add multiple of the same item with the SO
if I understand you correctly, yes
ah ok so thats good then
Would you guys recommend me to switch from dotween to leantween
Was hoping to get some help with getting UI elements that display what planet is what in the solar system of my game. Currently I managed to get these elements to orbit but they are not alligning themselves at the center of my camera.
Follow Script Code: https://gdl.space/yuxezogeqo.cpp
i thought having the prefab in the SO would mean that i had to just add the script to a empty game object and it would display the object listed
what script?
ok its working thanks for the help @knotty sun
If it helps. Here is my canvas aswell
i want to limit the movement of a recttransform to not overflow below the screen at all. so if i detect overflow, i just change the pivot to (0, 0), and the anchorMin to (0, 0) and the anchorMax to (0, 0), and position the anchoredPosition.y to 0. works well. but then i want to set the pivot / anchors back to their original values (0, 1) for pivot, and (0, 1) for anchors, but it messes up the positioning. even if i remember the localPosition before setting back the anchors and set it to that after changing them. any ideas why?
in the last line, i accidently set the world pos, but even setting the localPosition still has the same issue
Hi, I was wondering where do I go for help, as I'm trying to create a death floor, which works but it appears im clipping through objects on spawn
-Attempted elevating the characters/player
-Considered setting the movement speed to 0 but not sure how to call to another file/class
-changed the distance to reach the death floor
Using Scripts to create the deathfloor/checkpoint based system
