#archived-code-general
1 messages · Page 27 of 1
I think it's something with cs bullet.transform.position = bullet.transform.right * GameManager.instance.bulletSpawnTeleportDistance;
and this line DOES show the correct player position, right? Debug.Log(GameManager.players[playerId].transform.position);
bullet.transform.right is the right side of the vector, not the position of the bullet.
correct
So 0, 1, 0
oh
prolly meant += rather than =
So it spawns somewhere on the origin of your game.
^
Yes it does
that confirms it . you want to use += not =
Yeah he could do +=, but he could also just specify a bulletSpawnPoint and shoot it from that position.
Yup that worked
Thanks so much!
That way it actually goes with the gun if you rotate it.
Yeah
YES! or could use player.transform.right rather than bullet.right
I'm doing a manual raycast to check for mouse over tiles on my strat game map. it does NOT use the event sytem for this.
I would like to detect if the mouse is over a canvas UI element from within this component (so I can arbort/block my custom raycast tests)
I've got this code, but it is detecting hits on canvas elements that the mouse is NOT over. Note that the pointerEventData passed to the raycast take the event system itself as a parameter, rather than the current mouse position- could this be the issue?
graphicRaycaster.Raycast(new PointerEventData(EventSystem.current), canvasHits);
if (canvasHits.Count > 0)
{
Debug.Log("mouseOver canas element aborting raycast on map check");
foreach (RaycastResult hit in canvasHits)
{
Debug.Log(" " +hit.gameObject.name);
}
Cursor.visible = true;
onMouseExitTile.Invoke(previousMouseOver);
return;
}``` EDIT: never mind I got it... using ```EventSystem.current.IsPointerOverGameObject();``` works
You could try:
Express the mouse coordinate in the sprite coordinate
Find the percentage of the new position in the sprite
Use the percentage to figure out the pixel
Read the pixel from the texture 2D
you could do a manual raycast, the hitReult will have the UV( texCoord) of the object you hit. you can use that to sample the color in the texture. https://docs.unity3d.com/ScriptReference/RaycastHit.html
Does raycast work on UI element ?
if it has the appropriate collider components on it, yes.
If your UI is not in world space, it wont have a collider ?
you can always ADD a collider, but not sure about the world/canvas space stuff.
My enemy AI won't move unless I set their Rigidbody's physics material to slippery
Is there any way to fix this?
how are you moving the object? e.g. setting transform, applying force... etc
Applying force to the Rigidbody
if the friction is high, you may need to apply more force to get it to accelerate. (easy to push a large block sitting on ice, but hard to push it when it's sitting on say.. carpet)
hi ,
I remember there was a a way to get the current scene name or the current scene index
what is it ?
also note that the STATIC friction will be used when the object is still, and the DYNAMIC friction will be used when it's moving. So if they are very different, that could be tougher to handle...
checkout - think this has that stuffhttps://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html
How does one manage a system of counters in a clean scalable way? For instance, let's say I'm making an RPG, and there's two entities fighting: A and B. A uses a fire type attack but B is wearing armor that reduces fire damage, then C comes along and enchants A's damage to ignore armor. Which entity should be responsible for resolving these interactions?
I don't know if this question makes sense
There is no clean way when dealing with tags and stacking properties. The manager responsible for resolving the battles should figure it out. Lots of if statements.
ok so i need some help with a thing i wanna do, basically i have a text system set up, "see picture below", and i have a plaerprefs string for the player name. i wanna call the playername inside of the text which will be displayed in a text box, i do not really know how to do this and i was wondering if anyone had a solution, thanks!
I see you have a dialogTexture reference in that script, but I dont see a reference to anykind of Text or TextMesh component
thats in another script
normally, you would add one to your scene, then drag that scene object into your script reference. then in your code you simply use textRef.text = "someString";
you CAN do it THROUGH another object (dialog manager), but then you'll need a reference to THAT object in your script
if i did that wouldnt it ruin the other dialogue in the boxes
e.g. dialogManagerRef.DialogText.text = "some string";
I dont understand
im trying to make the playerprefs string, show up for the word "player" or something that i write for dialogue in the first picture
do you understand now?
no, I'm sorry- explain differently- I'll get it eventually
ok, so i have a playerpref string which is the players name. i have a dialogue box in my scene, with text that displays inside of it. i write the dialogue using the script in the first picture. and i want to take the playerpref string, and insert it into the dialogue i write, using some sort of code word, or some indicator.
but since i dont write the dialogue inside of VsCode and i write it inside of Unity idk how to do that
is the text that will display the playername a Text object referenced by the DialogManager? or is it an already existing text in there, and you just want to INSERT/APPEND the player name to text already inside on of those?
the playername thing in the first picture is irrelivent, it doesnt do anything
the playerpref is inside of the script and isnt on any text objects
perhaps I'm misunderstanding... do you want to just adjust a "string" rather than a dipslayed text? e.g. " Hello [PlayerName] how are you?" to "Hello Glurth how are you?"
yes, but the string corrisponds to the displayed text.
https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-7.0 I think this is what your looking for.... where you get the strings (Text component, playerPref, array of strings) is irrelevant to this function.
it probably is but im to new to c# to understand half of it
a simpler exmple: string playerPrefName = "Glurth" string originalString ="Hello [PlayerName]!" string finalString = originalString.Replace("[PlayerName]", playerPrefName); // finalString == "Hello Glurth!"
i think i get it lemme try
ok so i think i get it, now how would i go about translating that into the setup i have?
I'm afraid I don't quite understand the setup... but to get it into a text component for diaplay you do somthing like ...textComponent.text = finalString;
the circled item being a "Text" Component
does anybody know how i can add to remove the object again with rightclick in this code ?
using UnityEngine;
using System.Collections;
public class GridPlacement : MonoBehaviour {
public GameObject tilePrefab;
public float gridSize = 1;
public LayerMask placementMask;
private GameObject currentTile;
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, placementMask)) {
Vector3 point = hit.point;
point += new Vector3(0, 0.5f, 0);
point.x = Mathf.Round(point.x / gridSize) * gridSize;
point.y = Mathf.Round(point.y / gridSize) * gridSize;
point.z = Mathf.Round(point.z / gridSize) * gridSize;
if (currentTile == null) {
currentTile = Instantiate(tilePrefab, point, Quaternion.identity);
} else {
currentTile.transform.position = point;
}
if (Input.GetMouseButtonDown(0)) {
currentTile = null;
}
}
}
}
!code
in addition to setting the reference to null.. sounds like you want to "Destroy" the object
i tried it this way now
using UnityEngine;
using System.Collections;
public class GridPlacement : MonoBehaviour {
public GameObject tilePrefab;
public float gridSize = 1;
public LayerMask placementMask;
private GameObject currentTile;
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, placementMask)) {
Vector3 point = hit.point;
point += new Vector3(0, 0.5f, 0);
point.x = Mathf.Round(point.x / gridSize) * gridSize;
point.y = Mathf.Round(point.y / gridSize) * gridSize;
point.z = Mathf.Round(point.z / gridSize) * gridSize;
if (currentTile == null) {
currentTile = Instantiate(tilePrefab, point, Quaternion.identity);
} else {
currentTile.transform.position = point;
}
if (Input.GetMouseButtonDown(0)) {
currentTile = null;
}
if (Input.GetMouseButtonDown(1)) {
Destroy(currentTile);
currentTile = null;
}
}
}
}
Hello Guys 🙂
I am having trouble exporting my game to Android in Unity for a few days now. When I try to export the game, I get the following error message: Cannot build player while editor is importing assets or compilling scripts. The console is still empty despite this. I am only getting this one error message when trying to export. I am using the shortcut "CTRL + Shift + F" in Visual Studio to search for "using UnityEditor" in all my scripts, which is known to be the cause of this issue. However, I am not finding anything out of the ordinary. Sometimes, there is a script with "using Editor" in the Editor folder or the script name has "Editor.cs" at the end. Can you tell me what characteristics I should look for in order to solve this problem? I would greatly appreciate any help.
#854851968446365696 on how to post code
Hello,
SceneManager has many useful options, but I dont know how to get the Name of the Additive scene the player is currently in (the player can have multiple additive scene open but only one of them the player is considered to be in it ( the last one added ))
would this method be accurate ?
Scene[] scenes;
int lastScene = scenes.Length;
string lastSceneName = scenes[lasScene].name;
when I check for a colliders normal, sometimes the normal is on the side of the platform. Can I make it so it ignores the normal on the side? This is in 2d btw I can explain more if I don't make sense, thanks
do you have a reference to the player?
then you could do
playerGOvar.scene
to get the scene of the player
i still havent figured it out...
it doesnt work as gameobject.scene only gets the main scene not the additive ones
What have you gotten so far?
did you read what im trying to do?
Yes and he's already given you the solution..
The concern would be how much have you attempted to do.
Folks will likely not integrate/implement it for you - the hard part has already been done.
well my setup is very complicated at least for me so im having a hard time finding which value is actually the one i need to replace
how does the sprite rendering order work? I have a method that returns the name of the game object that the mouse is on and I have a grass tile placed on layer 0, and a transparent tree sprite on top of it placed on layer 3, but when i click on the tree I get grass from the method, lmk if u need more explaining or the code
show script
whats the differnce from a string with [] and a string without []
really
ur asking this in #archived-code-general not #💻┃code-beginner
Generating the tree:
Get tile method:
sorry i forgot what channel i was in
ah its an array
so can you not replace array strings?
you have to make a whole new array each time you trying change it
or just use a list
Oh you mean replace a string , then yea you should
when i do Examplestring.replace the function replace isnt there
for the array string
for the whole array or the entry ?
im confused 
Me too, I have 0 context what you're trying to do 
this is what im trying to do public string[] sentances;
sentances.replace
but the replace function isnt there
im trying to replace a string array i have so whenever in the string array the word "[player]" comes up it will replace that with a differnt string
loop through it no ?
idk what that is
ok lemme look
yea if you don't know an array linq mayb too much
but it is 1 line
i should probably learn about these things before i try implimenting them into my game lol
newstrings[] = oldstrings.Select(x => x.Replace("string1", "string2")).ToArray();
or sum
😖
that will replace everything right not only when the word player comes up
i need to learn about arrays first lol
have any idea about this?
replaces any string1 wit string2 in array
ur using tilemap right
no just placing sprites essentially
using perlin noise just placing sprite when the pixel is a certain color
dont know how to integrate it with a tilemap
so you do or dont want tree selection?
i do want it
are you using collider to click on or what
so rn when i click on a grass tile with a tree on it it returns grass
ok lemme explain how im doing this
maybe explain how u actually detect clicks first lol
the gameobjects and their positions are stored in an array when the terrain is generated, then when you click i take the mousepos x and y and look in the array and find the tile that is at that x, y and return it
How would I make it so that my Enemy AI will slow down the closer it gets to my player?
vector3.distance(a,b) < 2 // slow down
idk that is what i thought the problem was, but even when I changed the layer order it returned grass
so i dont really know what the problem is lol
ofc the problem is hard coding positions so it doesnt know which one to pick?
im assuming bc they have the same x, y
either manually add a third parameters yourself for a "zindex" or depth
It's a 2D game and the enemy is following a path to the player
or check it in the sprite renderer directly
if it's a certain size, grab front only
so use vector2.distance
slow down speed follow of the path
ok yea ill try that
So do
Vector2.distance(target.transform.position, transform.position) < 2;
```?
make it a bool
if(Vector2.distance(target.transform.position, transform.position) < myDistance){
//slowdown speed
}```
doesn't have to be 2..
just make it a variable you can set in inspector
never hardcode magic numbers
So should I replace
if (isGrounded)
{
rb.AddForce(force);
Debug.Log("Pushed");
Debug.Log("Force = " + force);
}
``` with
```cs
if (isGrounded && Vector2.distance(target.transform.position, transform.position) < myDistance)
{
rb.AddForce(force);
Debug.Log("Pushed");
Debug.Log("Force = " + force);
}
``` ?
prob not, wat is force ?
how are u moving enemy in the first place
// Direction Calculation
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 force = speed * direction;
um so you would change speed no?
Well I figured the easiest way would be to stop applying a force altogether since the enemy will still have momentum
oh sure you can do that
or set .velocity
I'm getting closer to what I want, but not quite
I don't think I want it to be possible for the player to make the enemy fall to its death by simply jumping over it
But its direction is not changing fast enough to make that possible
I can show you
ok
Setting the velocity directly will make it a lot more responsive than using forces.
Will it still be affected by gravity?
you might need to make a raycheck for ledges
put a full stop on velocity when you hit edge
Yes and no. It will be effected but setting the velocity will override the last velocity, That means gravity will get applied but potentially reset every update if you don't handle it. I'd recommend simply applying your own gravity and having full control of the enemy movement.
How do I change it from force to velocity? Here is my current method of handling movement.
// Direction Calculation
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 force = speed * direction;
...
// Movement
if (isGrounded && Vector2.Distance(target.transform.position, transform.position) > myDistance)
{
rb.AddForce(force);
Debug.Log("Pushed");
Debug.Log("Force = " + force);
}
can anyone help me with c#
If you have a coding question related to Unity, you can ask your question, with details, in #💻┃code-beginner.
I think I decided that I'm just going to leave it as-is
This problem has gotten too difficult to the point where its not worth fixing anymore
understood. easier to just limit the velocity manually when close enough instead of bursts of addforce
How do I limit the velocity as the distance gets closer to zero?
if (isGrounded && Vector2.Distance(target.transform.position, transform.position) <
myDistance)
{
rb.velocity = newdir*speed;
}```
or use MoveTowards once it's close enough, maybe it will work
Will move towards still apply gravity?
no it moves the transform directly
if ur on the ground tho why do you still need gravity?
only use movetowards if ur like close to player and on same Y pos more or less
idk I just use raycast for everything
Doesn't work
Freaking nothing works
Its too slow and I don't know how to fix it
I'll try #archived-code-advanced
lol doubt it's "advanced"
just take a break from it
come back to it later
mind needs rest for solution
hey, with Unity Splines, how expensive is changing the range of a SplineExtrude? I'm using a DoTween to animate the extrusion, but while it's happening it lags my game a lot.
Probably quite a bit, considering it has to remake the mesh
I would assume so, but instead tweeting the end point doesn’t hurt performance noticeably.
PID is mildly related
What’s PID?
Proportional integral derivative or something like that
Calculates desired velocity based on distance, so you don't overshoot, overcompensate, ...
How do I assign a reference to a script on my scriptable object?
If you are talking about scene object, you dont.
Nope, tis a script that's just chilling in assets, not attached to anything
What you want to do with the script. It is unusual.
Can scripts not be added as references on SO's?:0
Will that impact whether or not Unity will accept my reference? 🤡
Each SO is a weapon. The weapon needs a reference to a script, specifically written for that weapons, that holds methods unique to that weapon
It depends🤦♂️ Is it a component ?
So, the script is an other Scriptable Object ?
Does the script has data ?
It can be whatever it needs to be
What things can it be then frog man
Does the script hold data ?
what do you consider data
no
Can it be a static function ?
mmmmmmmmmmmmmmmmmmmmmmmmmmm
I see, I see. Hmm. When should a class be static?
Whenever it does not have a state.
When it does not make sense to have a state*
Math function by example
Yeah, alrighty. It is a bit of a weird one - the way ive done it, but I believe it does not have state. So, I guess it can be static. Will that allow me to pass it as a referencial?
Then create your script as a Scriptable Object.
Take a reference to your script in your second Scriptable Object
Then I will have one SO type per script, which I do not want
Use polymorphism if needed with SerializedReference
What is the real problem. Because I dont understand it.
Sure, I shall provide some more detailz
You said you wanted to add a functionality in your script (SO) which depends on the weapon.
1 SO per weapon + your generalised script
1 SO per weapon, indeed
In other words, we would use the Strategy Pattern
Idk about the generalised script:
I'm creating abilities for weapons. Each ability will be its own script. The weapon SO's need the ability to recieve a reference via the Inspector to some number of abilities
Are we still on the same page here?
Oh fk sorry
I've completely greifed this explanation. I've just explained the old way I was doing it...
One moment please
The abilities should be a prefab. Because it is going to contains a state (A life time).
I have a class that inherits from SO called Ability.
Each Ability SO requires some data:
- name(string)
- Sprite (sprite)
- AbilityData (script reference with unique ability methods)
AbilityData does not have state
AbilityData could be a SO
I don't want it to be, because then I'd have 1 SO per script
Excellent idea.
Is there another way?
You can make a prefab, use reflection, use Plain Old C#
A prefab of what sorry?
A prefab of your abilities, which you would spawn in the game. The prefab would contain the component that defines your abilities.
If your abilities have states, you will need to do that.
They dont have state
It is an alternative, like you asked.
You can also use Reflection.
Create a dropdown that contains a list of all the available function.
Then you can call the appropriate function on runtime.
Mmm but each weapon doesnt need to know every available ability - only its assigned handful
I'm not really sure why you are creating a AbilityData if each ability can only have 1 ability data.
You can still add function to a Scriptable Object.
Ability is a script that inherits from SO. I create 100's of ability SO's from that one template - each one representing a unique ability. I need a way to assign a script to each one of those ability SO instances
I'm probably explaining myself poorly...
Yeah, that functionality is an AbilityData (abstract class) that could be a SO with a function named "cast".
It still doesn't let me assign it, if I inherit from SO
It should
{
[SerializeField] private Sprite icon = null;
public abstract cast();
}```
that could be a way to do it
Ooh alright jeez that looks so similar to what I have but it smells like it could be exactly what I'm after... thanks lemme try that for a moment!
Here is small tutorial that shows how scriptable object can be use in a nested manner. (Didnt watch it completly, it may be shady, but at first glance it was showing what you are struggling with) https://www.youtube.com/watch?v=81kyAHy9gUE
whats the best way to make area-based environments, something like terraria but in 3D, where i have a 3D backdrop that will fade in, with specific area-based elements (a boiling hot sun in one area, that fades away when going to another, an ocean of water that obscures anything under where the player should be, that vanishes in the next area, an infinite wall of grassy hills behind the player, that dissapears in the next area), how could i go about achieving this effect?
i want these elements to be constantly present in one area, but fade out and unload as soon as they get to the next area
You want dynamic skybox ?
not a skybox
but an entire environment
ill set up what i mean.. hold on..
It is pretty hard to know what you want. Everything you ask does not seem like the same problem at all.
yeah, mainly because its hard to describe
ok i want something like this, where its a repeating, looping environment, with some elements maybe following the camera (like the sun), and some foreground elements like the water, that will completely fade out when entering a new area, and a new set of these elements will fade in, maybe some spooky trees or a bright moon with clouds
im wondering if i should spawn all these elements in whenever the player crosses to a new area, and unload the previous elements, or if i should have all of them pre set up so they can just be reactivated when the player enters the corresponding area
or if theres an entirely better way to go about this
none of these have to necessarily interact with the player or the environment, but just be there purely for visual effect
its not dissimilar to what terraria does, where there is different lighting and clouds and backgrounds for each area, but its in 3D, which makes it much more difficult from my perspective
Ahh, no okay so yeah I'd already thought of this, but again, it would mean I'd have a SO instance for each ability, and for each ability data
I've probably put fourth some confusing explanations, but now that I've been attempting to describe it for a while now, here's my most proper explanation:
I have ONE script, called Ability, which inherits from SO. I use CreateAssetMenu in this script, so I can create 100's of ability SO instances.
For each ability, I will have a unique script, AbilityData, containing methods that the corrosponding SO needs access to.
I do NOT want to create an SO instance for each of these AbilityDatas. AbilityData does not contain state.
I simply need to link each SO instance of Ability, to its corresponding AbilityData script
There is no "clean" solution. Personally, I feel like you are not seeing what a 3D level is versus a 2D level.
Normally, you would design your level such as those elements are part of the scene (Mountain)
You would then use Postprocessing, Skybox, Dynamic Lighting, Particles System, etc. to add more uniqueness to your "biome"
right, and im going to do that with a large part of my level (basically the entire foreground or actual landscape will be this way, completely set up by hand and using lighting and particles to make it more unique), but i want some of the background elements to fade out when the player approaches the next area
this is all very hard to describe
im trying to think of a good way to demonstrate this..
ok i got an idea, give me a second
ok so the player starts walking, and at first, the backdrop looks a certain way, in this case, sunny with green rolling hills, then as they walk into the next area, the old landscape fades out and the new one fades in, and as they fully cross into the new area, the next landscape design takes shape behind them
Most of that seems like a sky-box/background transition, like what Tarreria does
Oh you literally already said that haha
I've done some example
To be honest, the first one is probably exactly what you want.
Checking it out now(:
This is a skybox...
You want dynamic Skybox.
Otherwise, put those elements as Props in your level.
i think i get what you mean.. ill look into that more
When you do a level linear or open world. You do more than only the level itself, you do the surrounding also.
In this first example, I'd want the [CreateAssetMenu] on the Ability script. Is that legal?
You add mountains, tree, rocks, etc. in the zone that you cannot go.
Absolutely
I mean, you need to do it on the FireBall script
"Cannot create instance of abstract class"
All good. See that is SO close to what I want, absolutely. I just need to not fill up my create asset menu with 100's of options that I only ever use once, ya know?
this confuses me. do you mean to say that when you make a level, you make the props in the background or foreground with it and dont make it as a seperate part of the scene?
Use a script to create them 😛
Some part of the world cannot be reach by the player. Those part still contribute to the art of the level.
so you are saying that even unreachable parts should be considered parts of the level, if only visually
But again, it could be different for you.
If you are faking the 3D
Or not.
If you have unreachable part
Or not
should i be copy and pasting these rolling hills for the entire length of the level, or is there a better alternative
You make terrain.
?
i have a mesh already that i am using for the background, and i want it to be repeating to bring out the foreground elements more
but im just wondering how i should make it repeat
You create a low definition terrain to be part of your background. (All around your world)
Or you use Skybox
just a bunch of no-collision, smooth shaded meshes, that are hopefully performant enough to be repeated
wait i think we are on a different page
i want these elements to be 3D
i could make a 3D skybox
by having the main camera render over a skybox camera
but im not sure thats what you mean
Go look into the scene.
ill look at this
See how the made the terrain (background)
And do not use your mesh for the terrain as the terrain needs dynamic LOD.
You could theoretically make a low resolution of a terrain in Blender to be use in background. I would advice to use the Unity Tool instead thought.
Alright, I'm out.
Thanks for the help and example code @steady moat (:
How do I add light to particles? When I do, the light stays on and if I turn it off, it never activates with the particle effect.
not a code question
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Alteruna;
using System;
public class CustomNetworkManager : MonoBehaviour
{
public static CustomNetworkManager instance;
public Spawner spawner;
public List<Player> players;
[Serializable] public struct PlayerSpawns
{
public Vector3 SpawnPosition;
public Vector2 SpawnRotation;
}
public PlayerSpawns[] playerSpawns = new PlayerSpawns[20];
private void Awake()
{
instance = this;
spawner ??= GameObject.FindWithTag("NetworkManager").GetComponent<Spawner>();
}
public void SpawnPlayer(byte playerIndex)
{
var PlayerGO = spawner.Spawn(playerIndex);
var _player = PlayerGO.GetComponent<Player>();
players.Add(_player);
_player.Move.transform.position = playerSpawns[playerIndex].SpawnPosition;
_player.Look.Rot = playerSpawns[playerIndex].SpawnRotation;
_player.Look.transform.rotation = Quaternion.Euler(playerSpawns[playerIndex].SpawnRotation);
//PlayerGO.GetComponent<Movement>().transform.position = playerSpawns[playerIndex].SpawnPosition;
//PlayerGO.GetComponent<PlayerLook>().Rot = playerSpawns[playerIndex].SpawnRotation;
//PlayerGO.GetComponent<PlayerLook>().transform.rotation = Quaternion.Euler(playerSpawns[playerIndex].SpawnRotation);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
SpawnPlayer(0);
}
}
}
public class Player: MonoBehaviour
{
public static Player player => CustomNetworkManager.instance.players[0];
}
Player spawns, gets added to the Players list, everything seems fine but
I'm getting these 2 errors, I have no idea why
whenever you look up subtracting quaternions, you get something like this: C = Quaternion.Inverse(B) * A; which makes sense because you can't actually subtract them... but one thing I'm confused on that I can't find anywhere, does that mean B - A or A - B???
I'm no quaternion pro but I don't think it means either B - A or A - B
It means doing the B rotation the other way around, then the A rotation
I don't think quaternion additions and substractions make much sense for rotations
If you want to do two rotations, you multiply the quaternions instead of suming them (A * B means the rotation represented by A then the rotation represented by B)
But again, I don't know much about that so I might be wrong 😅
Could I get some help understanding how NativeParallelMultiHashMap works is there any kind of native data type I can use that works similar to an array of arrays? The unity docs are a little unclear
Why does this fail everytime? string pos = transform.position.x.ToString() + "," + transform.position.y.ToString() + "," + transform.position.z.ToString();
define "fail"
its in timer
and other calls doesnt call
and debug.log right below it doesnt say what it should
its saying 1's
and right below this command is to return 2
so that i define as fail
WAit i think im stupid
lemme try this
If you're using C# Timer class then you can't access Unity components from there, it runs on a separate thread
don't use the Timer class
https://github.com/akbiggs/UnityTimer here ya go dude
Just use this
Why would the server explode
The avatar of the awsome dude that wrote this awsome free lib
Ah
Rip his nose
I think my unity fail from like 8k logs
What to put in object arguments
my intelisence broke
oh nevermind
so this will work now?
It doesnt work
NOice everything except some small code works
Literally nothing is wrong stop
Finally goddamn
Haha never mind
Hahaha
Thanks for creating 2 of the same scripts
Hey, (sorry in advance if i don't have to do this, idk) does anyone knows about input system rebinding UI package?.. i posted on the channel and i'm kinda close to burnout because the errors are non understandable :/
Did you try following the pinned info in #🖱️┃input-system ?
I followed a YouTube tutorial tbh
However, the tutorial pinned doesn't show how to rebind :/
My input system works actually, but if i rebind, it fails
and i got multiple errors
why IJobParallelForBatch is missing in unity 2022?
is that not part of the jobs package?
how to know it is part of the jobs package?
https://docs.unity3d.com/Packages/com.unity.jobs@0.51/api/Unity.Jobs.IJobParallelForBatch.html?q=IJobParallelForBatch
package version 5.1 has it 0.7 seem not to have it anymore
not sure why
looks like the docu for 0.7 is not ready yet 😅
Hey...is it possible to delay in Update() using coroutine?
you cant use the yield that you can use in a coroutine in update
you can start a coroutine in update
Is there any other way to delay in update?
if you would halt the exicution of update your game would freeze for the time that you halt it
what do you want to do that would requiere you to use a delay in update?
I've an enemy object which checks if player is near it in update. If it's near it execute attack(). And I want to delay between attacks
use an if statement and a timer
^
either use a timer like @somber nacelle sad or start a coroutine and use a bool to only start it once at a time
private float timer;
public void Update()
{
timer += Time.deltatime;
//Run every 5 seconds or whatever you want
if(timer < 5f) return;
timer = 0;
//logic
}
OOOO...gotta research it. Tnx guys♡
The "bullets" are going in the wrong direction, am i doing something wrong?
If it doesn't do what you want then yes
it's set to move them to the orientation of spawnPoint so rotate it to wherever you want them to go
Oh thats probably it, thank you, also, if i move the character does the spawnpoint moves and rotates with it?
then it moves with the Wand object
Oh Ok, thank you
Hi! Please give me a tip about blending between two cinemachine virtual cameras. Both of them have POV Aim (so LookAt is None), and I'm switching by changing priority.
The issue is that virtual camera returns to its position before switching, but I need it to keep new position. I attach video to demonstrate it. Ideally, if disabled camera with follow view direction of the active camera.
IConnectionState was not Disposed! Please make sure to call Dispose in OnDisable of the EditorWindow in which it was used.
UnityEditor.Networking.PlayerConnection.GeneralConnectionState:Finalize ()
How do i get rid of this error
so, i have child objects with their own rigidbody but i still need the parent to be able to use their colliders. is there a way to make this work?
not a code question, also if those child objects have their own rigidbodies then they will move independently of the parent object and are likely not part of its compound collider
Hey i have an issue with unity crashing every time i open a script in my project does anyone know how to fix this ??
If I want to make a script that controls an entire level (ex all of the traps in an obstacle course) that triggers other scripts in sequence. Where should I put the script in the scene?
If the script only reference scene object, put it in the scene on a gameobject that could be called TrapSequence.
Not really. There is not enough information.
So basically an empty game object?
Well, i don't have any errors it just crashed when i click on the script
i'm using unity 2019.4.32f1 LTS if that helps?
is there anything wrong with the script when you look at it in your IDE?
also you can check the editor log to hopefully see the crash error
It's not only one script its every script even if i just created it
https://docs.unity3d.com/Manual/LogFiles.html, that path or theres a button next to the console to open it
How??
How do I move CloudBuildHelper class to Editor folder?
Yes (with the script on it)
is that one of your scripts?
Nope
wait do i open the script and then check the logs or the opposite
?
I'm having an issue with "The type or namespace name "PlayerSettings" does not exist in the namespace "UnityEditor"
when I googled it
that was the solution
but I can't find how to do that
Not really. Which script. What IDE you are using. Is it happening to every script ?
You put your script in an editor folder
See the first step in the video and how it put the script in a folder named editor. https://learn.unity.com/tutorial/editor-scripting#
Yes, every script
Oh I just create a folder and name it Editor?
Any ideas on why this is happening ?
Right ok I've done that and it fixed the issue thank you
But now it can't find the script 😦
No. No idea, with the information you provided. The only advice I can give you is to try from an empty project.
Ok
Is your script an Editor Script ... ?
you asking about the CloudBuildHelper?
that was what that person made in the forum post
it's not something that exists
the issue was your PlayerSettings script
Does someone how to fix this error? I tried removeing all the headers and on the error message.
I need advice for building the player structure for a multiplayer game, I've been trying using static player property for a while
could you guys let me know please?
I don't want to use a separate Player instance for every class related to it (movement, weapon and so on)
Wouldn't every player need its own instance? How else could it possibly work
oh no I'm talking about Player instances on different classes related to Player class, such as movement and weapon controls etc
So am I?
yeah that doesnt really work for multiplayer, using statics for players
as theres more than one...
A lot of the pretty decoupling patterns are hard to use as soon as you have more than one player. Or well, at least it was for me. I was going to do a losely coupled event queue to send messages between my movement, stats, inventory etc, but I realised it would be pretty unwieldy with multiple players.
I'm talking about instances of objects, not static "instance" variables
Those are different things
I was doing this
public class GameManager : Monobehaviour
{
public static GameManager instance;
public List<Player> players;
//Singleton stuff...
public void SpawnPlayer()
{
var _player = Spawner.Spawn(player);
player.initPlayer();
players.Add(_player);
}
}
public class Player : Monobehaviour
{
public static Player player => GameManager.instance.players[PLAYER INDEX HERE];
public Movement Move;
public Weapon Wep;
private void initPlayer()
{
Move = GetComponentInChildren<Movement>();
Wep = GetComponentInChildren<Wep>();
}
private void Update()
{
Move.doUpdate();
}
}
public class Movement: Monobehaviour
{
public void doUpdate()
{
//MovementStuff...
Player.player.Wep.doSomethingAboutWeapon();
}
}
public class Weapon: Monobehaviour
{
public void doUpdate()
{
//WeaponStuff...
Player.player.Move.doSomethingAboutMovement();
}
}
holy hell next time I'm writing this on code editor first
yeah this is what I was talking about
heya, im in need of a bit of advice, id like to give the player in my game the ability to spawn vegetation (flowers, trees, bushes, etc) on surfaces in the game, and i wanted to ask what would be the best way to go about doing this?
right now im thinking about creating an action that triggers when they press a key, which creates the corresponding flower/tree at the location of the cursor, but i cant help but think theres probably a better way of doing this
Hello! Anyone know how to get Light type in script?
How can I get a list of all the scriptable objects (of type Card that inherits ScriptableObject) that are in a specific directory?
I am doing: csharp var cards = Resources.LoadAll<Card>(directoryPath);
But it gives me an empty array
Just access the type property from the Light component . . .
I was usingg var component = go.getcomponent<Light>(); but it doesnt give me which type of light
so i can save it into json
Usually in games where there is object placement, there is a transparent version of the object that appears to show you the placement of the object before you actually consume it.
If you're trying to get the correct light component: area, point, etc., you need to insert that component instead of the base Light. If you don't know the derived component, then again, you need to access the type property of the Light component and use that to get the correct light component . . .
I thought all lights use the Light component?
Like theres no sub classes, or am I wrong?
Probably, I couldn't remember so I provided an alternate just in case their were separate components . . .
@deep fable I found this post: https://answers.unity.com/questions/1393857/resourcesload-for-scriptable-objects-can-it-be-don.html and it seems to imply that Resources.LoadAll is not what you want to be doing.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Mmh.. and is there any way to do that?
@subtle scroll Don't crosspost
Can someone help me with error in code?
Yes, read #854851968446365696 "Asking questions"
sorry, i didnt know where to put the question
Ok I've found a solution, but now there's another problem.
If I try to create a SO from code everything is fine.. but as soon as I recompile the project, I get a SerializedObject target has been destroyed error and the SO I created gets destroyed.
(I am trying to make a custom editor that creates a new instance of the Card ScriptableObject for every type that inherits an Effect class, but every time I recompile everything is wiped..)
is there anything i can do if i dont get any answer that works where i asked?
Wait and repost, or bump it.
This is a purely volunteer run server, there's no guarantee that anyone will want to help
I know, i just didnt wanted to crosspost
- I tried learning DI recently and i didn't get the part of defining a container. Am i supposed to simply hardcode them inside my object? What about testing, when i need to insert different containers with mock objects?
Are you saving the asset after it's created?
Yeah:
var newCard = ScriptableObject.CreateInstance<Card>();
AssetDatabase.CreateAsset(newCard, directoryPath + "/" + effect.ToString().Replace("Effect", "") + ".asset");
AssetDatabase.SaveAssets();
EditorUtility.SetDirty(newCard);
newCard.Effect = effect;
The problem may be that the Card class has an Effect field inside it which is an abstract class (and I set the Effect field from code instead of inspector).. I don't know if Unity can serialize the Effect field
Are you assigning a class derived from Effect?
Yeah
from code
Ok I may have solved the error
(basically I am making a card game and each card has a different effect and is represented by a SO. I have made a system that everytime I compile the project, it searches for all the Effect subclasses in the project, and if there isn't already a card associated with that Effect it creates one. Now it seems to work!)
Cool, what was the fix?
You want to lookinto: https://docs.unity3d.com/ScriptReference/SerializeReference.html
Yeah I also used that and now I can even change the serialized fields of the effect of the card, that's awesome!
Essentially, get a direction that points towards your target, and look towards that
Sorry I don't remember what the exact fix was, but it should be the fact that I moved the code that does that from a custom editor to the OnEnable function of the Card class (which is the SO), because effectively I didn't need a custom editor (and I read that custom editors can cause this type of problem)
(If you want I can show you the code)
This is getting needlessly hostile.
<@&502884371011731486>
Don't get abrasive please. No need to be insulting
hey i didnt start the insults if u scroll up
but u right, this aint worth my time
I think there's a function called LookAt
Try using the words look at, instead of point towards
look at dont work in 2D
Okay
But this is the basis of it
var dir = target - transform.position;
it's literally just transform.right = dir;
Look up how to get the direction towards another object or something
Yeah you'll need a direction, don't pass the position of the other object directly
I'm confused. If you got all of these results, what have you tried? You should have some type of code . . .
da boy can't read
Okay, but did you actually try any of those links bc I've looked at a few and they provide answers. That's what I'm confused about . . .
Does TileMap.SetTile have a performance cost if the Tile being set is already set there? Should I do my own check and only call this when I know the Tile will change? eg, when the user action is causing the TileMap to preview a change which will cause potential calls to SetTile every frame.
not 100% but it may cause whole tilemap to refresh each time
@swift falcon but anyway, they were correct before, don't cross-post, especially since this is a beginner topic/question. I'd check out those links you posted from your search. They have the answer . . .
Thanks, probably worth me checking just to be safe then.
Also, it's really weird to think that the entire TileMap refreshes every time a single Tile changes. Shouldn't it just expand outwards from the change and update rule tiles?
Is there a way to set a custom icon for a specific SO? (because for now, doing EditorGUIUtility.SetIconForObject sets the icon for the script, not for the individual SO)
bump
Hi, would this work for reading an array, list, hashset, or dictionary from a file?
/// <summary>
/// Read a collection that can use a signature to reference length.
/// </summary>
/// <typeparam name="ColT">The collection's type (e.g. string[], List<int>, HashSet<GameObject>, etc.)</typeparam>
/// <typeparam name="SigT">The signature type, must be numeric integral type. (sbyte, byte, short, ushort, int, uint, long, ulong)</typeparam>
/// <typeparam name="ValT">The collection's stored type (string, int, GameObject, etc.)</typeparam>
/// <param name="signatureReader">The function that reads the signature from the file.</param>
/// <param name="valueReader">The function that reads the values of the collection from the file.</param>
public static ColT ReadCollection<ColT, SigT, ValT>(Func<SigT> signatureReader, Func<ValT> valueReader) where ColT : ICollection<ValT>, new() where SigT : struct, IConvertible
{
int count = (int)Convert.ChangeType(signatureReader(), typeof(int));
ColT collection = new ColT();
if (collection is ValT[] array) // Is Array
{
array = new ValT[count];
for (int i = 0; i < count; i++)
{
array[i] = valueReader();
}
return collection;
}
// Isn't Array
for (int i = 0; i < count; i++)
{
collection.Add(valueReader());
}
return collection;
}
What about JSON serialization? These 3 collection types are supported out of the box
Json is too wordy
Hey im getting a really weird issue where a game object only delete if the scene view camera is facing it, so if i go full screen or turn the camera away it wont delete ```
void Update() {
GameObject objectToDestroy = GameObject.FindWithTag("PLEASEWORK");
if (objectToDestroy != null)
{
StartCoroutine(DestroyObjectCoroutine(objectToDestroy));
}
}
IEnumerator DestroyObjectCoroutine(GameObject objectToDestroy) {
yield return new WaitForSeconds(3);
Debug.Log("DESTROY");
Destroy(objectToDestroy);
}
And? As long as it's performant, read and written right, what's the issue?
File size, I'm making procedural worlds so I want to compress the files as much as possible, json adds unnecessary string data for assigning keys to values
With this I just read and write in the same order and I'm good to go
Then you'd want a custom binary serialization
I think that's what I'm doing
With a file format you create yourself
Do you know if my code would work, because I've actually already created a binary serialization script but I want to add this collection reader/writer
is it normal to have so many children on a rigged enemy model?
Yeah that works
ok, thanks
is it normal your body has about 206 bones?
yeah
alright, just thought maybe there was an optimisation to condense them somehow perhaps
thank you fellow cat enjoyer
there is the option in the model importer to optimize all the bones away that you dont need
o i will have a look for this, thank you
Does not seem like the script you are showing is the issue. But, you could maybe try Destroy(objectToDestroy, 3) and call the actual function once. if (isBeingDestroy) return;
Yes it is normal. In fact, you will find yourself with even more bone then that when you try to have better animation.
whats a quick and easy way of giving the user playing the game with some sort of message like an alert/notification
UI
UI
Toggle a UI element
so then learn how you can formulate a better question
what? just show a popup with a GameObject.SetActive
maybe you should ask in #💻┃code-beginner then
all the info i got i already knew
again so then learn how you can formulate a better question
hi, how could i get an array/list of all the objects the mouse is over in a 2d game? thanks!
the question was perfect
if you say so
why u gotta be rude and sarcastic
@whole yew, the most fast and easiest way of showing a notification to a player is to toggle with gameobject.SetActivate(true) where the gameobject is a UI Panel.
If it is not what you meant, then your question is not formulated correctly.
hmm, I thought of that but quickly thought against it because if I were to stack like 3 notifications then they will be clumped
I was thinkin something like spawning in a text object with a moving animation and then quickly fades away
Your question is not: whats a quick and easy way of giving the user playing the game with some sort of message like an alert/notification
But more about patterns
You should look into what patterns can be used to make a clean UI.
You can queue up notifications (with a Queue<T> collection), and have a script look at the queue and manage the UI
dotween is not, in my experience, something you necessary want to use for UI. You can use conventional Animator + Animation.
my project is almost near the end of finishing im just polishing stuff up right now and need a dynamic way of notifying the user of some stuff but nothing too complex cause im lazy and its not that important
Dotween would be the easiest way of doing the animation yeah.
And probably more performant, since conventional Animator will redraw the entire Canvas each frame, even if there's no movement
I prefer the conventional Animator because it has more feature and can be use directly by Artist. It also come with built in statemachine and act like a good layer between your art and your logic. If performance is an issue or a constraint, then you might want to go with Dotween like suggested.
Also, it is easier to setup with an Animator as can record/preview "your animation".
how can i configure vscode ? Its already connected tp unity and i have the csharp extension, .net installed, it just doesnt highlight errors
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
!vcode, why isnt it vscode uh
i followed the thing ,all that i did was set vs as the preference in unity, still no underlining
oh nvm i did the first and not the second link
im so confused
rider has better support for unity
eww rider
have you tried it?
you better start liking good software, because you're aspiring to author it
jetbrains stuff is not for me sorry
bump
what is your goal?
oh nevermind
i'm not sure what the answer to your question is
sorry
has anyone had any experience with an odbc data connection screwing with the new input system?
void Start(){
DatabaseConnectionController.OpenConnection();
DatabaseConnectionController.CloseConnection();
Resources.LoadAll<Item>("").ToList().ForEach(x => ItemMemoryReference.AddItem(x));
SceneManager.LoadScene("GameScene", LoadSceneMode.Single);
}```
made this and kept removing things until the input system in the "Game scene" that gets loaded worked.
it only works when the connection is never opened nevermind closed
```csharp
using System.Data.Odbc;
using UnityEngine;
public static class DatabaseConnectionController
{
public static OdbcConnection connection;
private static readonly string connectionString = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+ DirectoryLibrary.DataBaseDir +";";
public static void OpenConnection(){
// Debug.LogError("");
connection = new OdbcConnection(connectionString);
connection.Open();
}
public static void CloseConnection(){
connection.Close();
connection.Dispose();
connection = null;
}
}
chatGPT canne waffle an answer so i got no ideas left haha
this only happens in build mode btw, works fine in editor
Are you talking about Dependency Injection ?
There is no connection between the Input System and ODBC...
Do you have an error in the Editor ? In the console.
exactly there should be no interference but somehow, when i dont open the connection it works, but when i do it doesn't.
no errors in the editor console or build logs at all
keyboard just ceases to exist (mouse works fine so the input system does kinda work?)
The issue seem complex because it is larger then your code. If I were you, I would not use ODBC.
Keep it simple. Learn. Then you may want to attack harder issue.
Question, if I'm going to have a lot of scenarios to allow the player to move like below:
if (hit.transform.gameObject.tag == "Red")
{
MoveDown();
}
if (hit.transform.gameObject.tag == "Blue")
{
MoveDown();
}
if (purple && hit.transform.gameObject.tag == "Purple")
{
MoveDown();
}
Is there a better way to put this? Because there's also going to be scenarios where say if you're purple - you can only move to red or blue. I know this works, but it's ugly and requires more work than I'm sure necessary
Hey guys, I'm having this idea which I have no idea how to realize.
Essentially I'd like to make a 2D dynamically curved textured line. In my specific case I'd like to make a sort of animated "magical beam" which can be curved and adjusted. I'm however unsure how to do this.
I've tried LineRenderer with custom Sprite Shader, which takes textures from Texture2dArray based on time. That however results in all tiles using the same sprite at the same time. As the TileRenderer tiles the shader itself, I can't offset some tiles etc. I also can't let the TileRenderer stretch the material, as I don't know the final length of the line in advance.
TL;DR: Is there any way to create a dynamically curving animated line textured with tiled, individually animated sprites without building it from ground up?
For reference, the gif is what I have now, and is almost enough apart from the fact that I need each of the segments (not of the line itself but rather the tiled sprites) to be animated independently of all others, i.e. in a random-like manner.
Is there something like Physics.CheckBox for any mesh (basically, is there anyway to do Physics.CheckMesh).
I'm not sure what you are asking
If not, what would be a good way to do this, because I need to be able to find out at any point if my object is touching something, and I will not ever know what type of collider it is.
You need to know the type of collider?
Check Sphere* seem enough for your need
Yeah I guess so thanks.
There is a lot of function that can be use: https://docs.unity3d.com/ScriptReference/Physics.html
Oh, thank you.
Also, you have on collision enter
I don't really want to use that, because I want to be able to call this in a seperate event, but sphere cast or check spere should work
ClosestPoint works fine too. If your mesh is convex.
You have any suggestions on my question above?
Subdivide your logic in multiple script.
{
MoveDown();
}
it is hard to find a good architecture because of how little I am working with.
Otherwise, you might want to look into Polymorphism
In fact, you probably should look into polymorphism
// NotSupportedException: Specified method is not supported.
// System.RuntimeType..ctor () (at <0da48681ced7494d83ae6a612d2206fc>:0)
// UnityEngine.Resources:LoadAll(String)
// TG.Frameworks.NodeTrees.Editor.NodeTreesUnityLoadProcessor:.cctor() (at SOME LINE)
// UnityEditor.EditorAssemblies:ProcessInitializeOnLoadAttributes(Type[])
static NodeTreesUnityLoadProcessor()
{
_nodeTreeObjectsDictionary = NTStaticBlackboard.GetAllNodeTreeObjects();
if (_nodeTreeObjectsDictionary is { Count: > 0 })
{
_nodeTreeObjectList = new List<INodeTreeObject>();
foreach (var values in _nodeTreeObjectsDictionary.Values)
{
_nodeTreeObjectList.AddRange(values);
}
}
else
/*THIS LINE =>*/ _nodeTreeObjectList = Resources.LoadAll<NodeTreeSO>("").Cast<INodeTreeObject>().ToList();
OnUnityBoot();
OnUnityLoad();
}
```First time I'm seeing this and I have no idea what it is
- Yes, but not about any specific framework. I write my own poor version to understand how does it work and that's the problem i face currently: need to hardcode the containers
Dependancy Injection is mostly implemented with Reflection
The results of Resources.LoadAll<NodeTreeSO>("") cannot be cast in INodeTreeObject
- I get this, i mean there has to be containers defined. Those with bindings, a set of rules according to which instances are provided. And i assume i have to create new instances of them all over the place since they're plain objects
- However, with this approach there's still direct dependency upon given types. Furthermore, i can't change containers, for example for testing or for modifying the game's behaviour, etc.
Changed to OfType, same error, no StackTrace. NodeTreeSO implements INodeTreeObject
What is the content of Resources.LoadAll<NodeTreeSO>(""). Results
var listOfNTO = Resources.LoadAll<NodeTreeSO>("");
foreach (var l in listOfNTO)
{
Debug.Log(l.Title);
}``` Prints fine. The list of ScriptableObjects is not empty
Not sure what you means. Give your current code.
Do they derive from INodeTreeObject ?
You could try to use a foreach instead of Linq to find out more.
- Nothing is wrong with any code, nor am i near my laptop. It's a purely theoretical question. Are you familiar with di containers?
Yeah, I was afraid of that, sorry. 😄
Basically I want to be able to have a script or object of some sort, into which I can put in a set of sprites and set of points. Based on those, it will generate a curved line passing those points, and will be textured by those sprites. But additionally, I want those sprites to be animated, e.g., randomly.
I tried my best to find something existing that coincides with my desired end goal, best I could find is the Mutation from Enter The Gungeon, e.g. see here:
https://youtu.be/MwHx6dOj_N4?t=862
Now I suspect the gun in the video is created as a stream of many projectiles dense enough to create the feel of a beam, but I'm hoping to create a single object, as I don't care about collisions, damage, etc.
Hopefully that explains it a little bit better.
public class NodeTreeSO : ScriptableObject, INodeTreeObject, ISerializationCallbackReceiver``` Yes. The error is always at the Resources.LoadAll line when it shows a StackTrace, so there isn't even Linq involved in the last code snippet
I'm familiar with Dependency Injection. But the one I used/created all use Attribute and Reflection and did not require container.
Use Array.ConvertAll instead
Look into https://learn.unity.com/tutorial/rigging-a-sprite-with-the-2d-animation-package#6017535aedbc2a69ae9b3b9e
You will be able to transform your sprite at your will like an animation. (An animation can be done in code)
An other solution would be to create particles effect.
That's an interesting perspective on the issue. I didn't think about that. I'll look into it, thanks. 🙂
- Well, maybe i name things wrong. That part when you define lifetimes for types: scoped, singleton and transient. They're stored within a single object, according to my knowledge this object is called container. Reflection and instancing happens way down there and it works flawlessly, the problem is storing scopes. Since "container" is a plain object, it means i have to instantiate it and register types there with their lifetimes. What is unclear to me is where are they supposed to be created. If i define them directly inside my actual objects, i don't remove any dependency, i just overcomplicate everything. So what is the "right" way to provide those containers is my question
You use Reflection to get the Reference of your class
[Service]
public class AnyServiceImpl : IAnyService {}
You then instantiate them from your ServiceLocator/Container
You need to create it.
It is how I would name it.
- I have never been to attributes. Is there any short summary of what would it do in this specific case, or is it too long and i should learn it myself?
Learn yourself.
- Okay, thanks
would someone be able to rate my project structure? Either by joining a screen share or me sending a video of the project? It would only take about 5ish minutes.
If so, could you dm me? Because I can do it anytime tomorrow (it’s 12am for me rn)
Will do. Thanks
ok 🫰
I'm making a solar system game/generator which lets a user select one of the 7 main sequence star classes to generate with realistic yet randomized values such as radius, luminosity, color, temperature, etc. All of the actual value generation is being done in my StarProperties class below (1st link). The second link is my SpectralTypeButton class which is attached to all 7 buttons representing each star class you can pick in the selection menu. All the calls to my random value generation are in this class so that when a user selects any of the available classes, the data is then generated, and for now, displayed on screen. The last link is my SaveManager class which I wrote so I could save the values generated within StarProperties. I would really appreciate it if someone could help me understand how to link my SaveManager to the generated values so they actually get saved. I've tried a bunch of stuff but the save file only ever returns 0's for the double values and false for the bools. Saving data is entirely new to me. 😄
https://paste.myst.rs/an75zluq
https://paste.myst.rs/1s3we1xa
https://paste.myst.rs/3f5q8iew
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
I'm having an issue with a bug where my slime can get hit,but no matter how many times I hit it,it can't die.(Code for the slime:https://paste.myst.rs/15nn8y3v)
does the data that gets saved to disk make sense?
Wdym?
Also,I'm trying to follow a tutorial for this program.I'm at around 46:20(Tutorial here:https://youtu.be/8rTK68omQow)
Guide on how to build a top down 2d RPG from the Ground up in Unity 2022. The goal of this crash course is to cover as many relevant beginners topics as we can but linked together in actually building out some prototype mechanics for a potential game.
Better Knockbacks Update Video https://youtu.be/yna_u1OASy0
Scripts and Project https://www.pa...
you seem to write a xml file called currentSolarSystem.xml to disk
does the values in that file look like you expect them to be
No... I said they are all 0 for the doubles and false for the bools. It's saving the default values for each one no matter what I try.
Luminosity, for example should be huge, like 425,000,000,000,000,000,000.00
i assume you assign activeSave via the inspector?
You mean by attaching my SaveManager script to an empty game object like so? If so, then yes. 😄
do you set the values of the activeSave variable via code?
i cant find any reference to that in the scripts you posted
I do not, as of right now. I tried like 8 different ways but none of them worked. Still kept getting all 0's and false. lol
if you not set the values in any way then the default value you provide via the inspector then
its gone save the values you can see in the inspector
Yes, I know that. In my original post I was asking if anyone knew how I could. Because I tried several ways and none of them worked.
just the usualy way you reference variables of other class instances
get a refrerence to your SaveManager component that is on that SaveManager gamobject
then you can do
saveManagerVar.activeSave.savedStarAge = 99.99;
I tried that several times and it never worked. Here is what I tried just now and still nothing.
I did this in StarProperties.
void Start()
{
SaveManager.instance.activeSave.savedStarAge = Age;
}
can you see that the values have changed in the inspector of the save manager after this is been called?
The value is still 0.
ok lets test the save part only
just put some test values into the inspector while the game is running
delete the save file
then save via the save function
does it contain the test values
breaking down the problem into smaller and smaller parts until you can solve / test them is the way to go
Yeah, I deleted the file so it would be a brand new one.
Then I put 9.7 for the age as a test. Saved it.
Quit the game.
Restarted the game, loaded the save. And the value was there.
so save and load seem to work
its only setting the data that need to be saved seem to be the issue
yes
try moving setting the data out of start to a later point that might be the issue
I thought that might be it too but wasn't sure where else to put it. Any ideas?
why not put it into GenerateStar like in line 73 of SpectralTypeButton
then it should set the values when you generate a planet
and then you can call save after that
okay, I'll try that real quick
OMFG, you're a genius!!
😄
That worked
I've been struggling with this all day lmao
nice glad its working now
Thank you!!!
Just an idea, but if your class is called SaveManager and the field is named activeSave, you don't need to prefix all your fields with 'saved', it's redundant . . .
Yeah I know, just my OCD brain making sure everything is as readable as possible.
Anyone know how I could replicate like the acceleration of addForce using rb.velocity? My brain is fried so I cant think of anything :/
use lerp to animate your current speed to move speed based on an accelerationRate. use an AnimationCurve to further customize the acceleration . . .
I never knew that existed lol, lemme go check it out. Thanks
rb.velocity += your direction * speed would be ForceMode.VelocityChange - ForceMode.Impulse is the same except it factors the mass. I'm not sure how exactly, I assume (total force /mass).
The 2 forcemodes remaining are the same essentially except they factor in the fixed deltaTime. Something like your normalized direction * speed * Time.fixedDeltaTime for ForceMode.Acceleration, and I guess ForceMode.Force looks like
rb.velocity += (Time.fixedDeltaTime * speed * normalizedDirection) / mass
not 100% sure that's how mass is factored in, someone else can chime in
yeah, Impulse is the same, but you add / mass at the end . . .
Thats about what I did too: https://www.youtube.com/watch?v=96cIYun83FE
Yes, these are actual 1:1 size stars of 1400000000m big or 80x as big!
Star Trek TNG, And all games since just use like particle effects... Impressive, but this warp effect I invented and many said could not be done has been done. ENJOY!
We run a guild. Opportunity: I can teach you how to make games for free better...
Thanks for the detailed description 🙂
Ah, mine isn't like that. It'll be more akin to the system viewing and interaction in Endless Space 2.
Yah you can do that with mine too, this is just warp.
My game is like an Elite Dangerous, except the skybox is realstars
and when you go to wrp, the stars become real game objects
and then the skybox is painted when you exit warp
Nice, I'm just doing one system, generating realistic ones with tons of other data and randomized system history's like DF. 😛
pretty sure no one's ever done this,
Steve if you want to work with Starfighter General, you can, I will not have very pretty stars at first
So if you going pretty route, I can drop youcode n stfuf
My code is similar in Star code types, I researched emon youtube
I'll think about it. My thing is in VERY early development and I'm doing it purely as a fun little side project.
Once I get all the relevant physical data setup correctly I'll be rendering the star in the system.
Then planets.
Ok, let me know if you can make em look pretty
I have it already to position n stuff
I'm an artist first, programmer second so I should be able to. Just need to learn how with Unity first. lol
Hey, want my proc gen star code? I can jump start you
Wait...
There's a bug in UNITY for large negative value entities
And ECS isn't good for a nub
Yeah you do you, stay in touch tho man
the accelerationRate determines how fast you move from start-to-finish, and the AnimationCurve specifies the rate of change from start-to-finish . . .
that'll be fun for you, I'm doing anything nearly as expansive as a whole galaxy
(though I will have a "galaxy" background of sorts though for realism)
Well it works like this
Make one system
And then you can just roll it 1 million times
We could roll it 500 billion times
but huge galaxies are too lonely for MMO crowd
They want to see people a bit
If you can randomly generate a system, planets & star(s), and make it look pretty, that's key. I see you're doing composition of stars by element,maybe you could do dynamic textures based on taht
I mean we both can do it, but lets reconvene when we both have more done
Proc gen galaxy for me aint' for another 2 months or so, lots of work to do before then
lol, for sure
I only plan on doing singular systems but I'll def keep you updated on the progress. The actual game objects and graphics are getting closer every day haha
Hello! I have a script where I want to be able to right-click and identify if my cursor is pointing at a sprite and if so what sprite. Googling tells me to edit a sprite's "OnMouseOver" function but I only want to check in this one script, not edit every sprite I have in the scene. My relevant sprite characters all have colliders, if that helps.
If it was 3D I could do a line trace but I don't know the equivalent for sprites.
Visuals don't matter in this case. Only the type of physics that you're using(colliders). If it's 3d, you use a ray/lineCast. If it's 2d you can use OverlapPoint.@kind grove
OverlapPoint? Thanks.
@cosmic rain I've got it working, but the gizmo I am drawing only appears in the scene view. Is there a way I can get gizmos to appear in game view? Or is there some asset pack I can get with debug spheres/lines I can render on screen?
Debug gizmos should appear in the game view in the editor(if you have them enabled in the game tab). They wouldn't work in a build though.
Ah, the dropdown is a toggle. Nice.
Any way to get the absolut scroll distance from a scroll rect? The event (and normalizedPosition) only give the normalized (0 - 1) position, do I have to use content height * normalized position to get the scroll position or is there something internal?
Basically l want to do a reload once the scroll rect is pulled down > 400 units while its at the top
Hey all,
Is it possible to change a canvas's color at runtime and somehow also control the alpha? It seems to revert to a 0 alpha (and is therefore transparent) when modifying the color attribute of the Image component, but when attempting to modify it through script I get the error "Cannot modify the return value of 'Graphic.color' because it is not a variable"
What element exactly are you trying to color? Canvas doesnt have a color property
Inside the Image component
Image has a color property
You can change it however much you want
Yes, but for some reason it automatically sets the alpha to 0 and it won't allow me to change it through a script
myImage.color = whatever;
You should probably just fix that first issue
Rather than putting a bandaid on it
If you are trying to do Graphic.color, Graphic is a unity defined variable, try renaming the reference to the image
I can get it to change colour no problem, but it automatically becomes transparent
You must have an Animator or a script setting it
Nah
He's trying to do this
image.color.a=1
oh ok 😄
When testing I can see that the colour itself has changed, but for some reason alpha gets set to 0 so it isn't visible
You'd have to do:
Color c = myImage.color;
c.a = 1;
myImage.color = c;```
But within the inspector I have it set to 255
Your code is changing it most likely
Otherwise it wouldn't change
I showed you how twice now
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
You're setting canvas group alpha to 0
Also it's 0-1 not 0-255
Yes, that was intentional, but that shouldn't affect the alpha of the canvas itself
The canvas itself has no visual appearance
It affects all components under the group
Including images
So based on this, I'm assuming the colour attribute itself has its own alpha?
Alpha is part of color yes but it's irrelevant if you're setting the canvas group alpha to 0
The canvas group alpha is for when I go to do the fade in (in the coroutine that comes after)
If I'm making a top-down game, how do I make it so that objects appear in front of the object when the player is behind it and behind the object when the player is in front?
Currently, the player is always in front even when it's not supposed to be
I think I've realized the problem, the colour that I had set inside the game object (that the canvas colour gets set to at runtime) had its alpha set to 0
All fixed, thank you for your help and clarification. Sorry if I'm a bit of a pain sometimes. I appreciate your patience
are you trying to say you are making a 2d top down game with walls, and you'd like the player to interact with the walls naturalistically?
Ehh, I think? I'm making a 2D top-down game and I need to draw the player either above or below things depending on where it is
So in the first image, when you go in front of it, the object is still drawn on top when it's not supposed to
the simplest way to do this is to model your world correctly
your characters should be in the xz plane, standing up, as billboards, with a constraint that aligns them to the camera look vector (-camera.transform.forward)
you should not be building your game in xy
for a top down view
Thas crazy I did Not know you could do that
is there a tutorial
Luckily this game is a test so I can just fix that in my actual game
I looked up top-down stuff but I didn't find anything
it's best to always model your game in the unity world as it makes most sense physically / naturalistically
2d games aren't physical but they can behave naturalistically
so you can give your characters 3d box colliders while being 2d sprites
it will make everything easier
It does sound easier but all the videos I'm finding for how to do it build the game in xy, and I don't have much experience with the camera or 3D space. Do you happen to know any good videos or something I can learn from?
actually it might not be that bad I'll just try it
hmm not sure
it's pretty clear
unfortunately most youtube videos about unity development are made by people who have shipped 0 games
real I learned everything from highschool classes so that about sums up my experience
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed = 3f;
public Transform movePoint;
public Grid grid;
public LayerMask whatStopsMovement;
void Start()
{
movePoint.parent = null;
}
void Update()
{
if (Vector3.Distance(transform.position, movePoint.position) <= 0.1f)
{
HandleInput();
}
transform.position = Vector3.MoveTowards(transform.position, movePoint.position, speed * Time.deltaTime);
}
private void HandleInput()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
if (Mathf.Abs(verticalInput) == 1f)
{
Vector3 potentialPos = movePoint.position + ConvertToIsometric(new Vector3(0f, verticalInput, 0f));
if (!IsObstacleInWay(potentialPos))
{
movePoint.position = grid.GetCellCenterWorld(grid.WorldToCell(potentialPos));
Debug.Log(movePoint.position);
}
}
else if (Mathf.Abs(horizontalInput) == 1f)
{
Vector3 potentialPos = movePoint.position + ConvertToIsometric(new Vector3(horizontalInput, 0f, 0f));
if (!IsObstacleInWay(potentialPos))
{
movePoint.position = grid.GetCellCenterWorld(grid.WorldToCell(potentialPos));
Debug.Log(movePoint.position);
}
}
}
private bool IsObstacleInWay(Vector3 potentialPos)
{
Vector3 currentPos = grid.GetCellCenterWorld(grid.WorldToCell(transform.position));
Vector3 direction = grid.GetCellCenterWorld(grid.WorldToCell(potentialPos)) - currentPos;
float distance = Vector3.Distance(currentPos, grid.GetCellCenterWorld(grid.WorldToCell(potentialPos)));
RaycastHit2D hit = Physics2D.Raycast(currentPos, direction, distance, whatStopsMovement);
Debug.DrawRay(currentPos, direction, Color.red, 1f);
return hit;
}
private Vector3 ConvertToIsometric(Vector3 pos)
{
Vector3 isoPos = new Vector3();
isoPos.x = pos.x - pos.y;
isoPos.y = (pos.x + pos.y) / 2;
return isoPos;
}
}
any ideas why it moves one more additional cell? upon tapping it once lol
@vagrant harbor A bit to much code for me to debug in my head at this early hour, but what happens if you fire up the debugger and inspect the values as update executes?
it's alright dw i appreciate the help lol. it might be something obvious that'll come to me when i eat lol. hope you have a good morning:P
hey so can I create a C# class library that I can share across the game and some other .net project?
upload the library to git and install the package via the package manager . . .
how am I supposed to generate a package?
you have any docs on this
what about importing a .net standard dll?
I can just compile it and import it right?
ok great
it works
thanks anyways
You can easily do this with no coding by setting the pivot points on your player and other models at the bottom center. Then going into the project settings -> graphics -> Set the camera settings to custom axis then put Y axis value to 1 and others to 0.
Thas crazy I’ll try
It might change the colliders for your objects when you change the pivot point so, keep that in mind.
Okie dokie 👍 I’ll try it and see how it works, thanks
And one last thing, make sure you set your sprite sort point to pivot
yes, importing .dll is fine . . .
@vagrant harbor Not sure what you're trying to show, but that's not what I meant :). In VS put a breakpoint at the start of your update method and press the "attach to unity" button (looks like a green play button).
You might need to move the breakpoint into the parts triggered on a button press though.
can I change my full screen in a webgl app through the code (I know under the app there's a button to make it go full screen but can I do that through code using screen.fullresolution or is there another way or no way at all)
Is there a built-in way of handling combination presses of KeyCodes?
Sort of
You will probably need to get the pressed key using this: https://docs.unity3d.com/ScriptReference/Event-keyCode.html
And store it each frame I guess, and then check it with an update method
Kewl thanks!(: Looks interesting
What's the difference between these two lines?
new List<KeyCode>() { KeyCode.LeftShift }
new List<KeyCode> { KeyCode.LeftShift }
Nothing
A list has a paramtererless constructor so you don't need to specify () if you initialise it with predefined values (which in this case is the keycode you added)
In your case you could store it in a list like this, and use Enumerable.Contains() on the list to check if the list contains a specific value.
Oh yeah alright, awesome:D thanks
I made a game on unity as a gift for someone so I don't want to publish it. I only want one person to play it. how can he download the game without having access to my computer? It is easy on android but his device is ios.
Well Im not sure you can even build to ios without a developer account
I can build to my phone via wired connection. also I activated developer mode on settings
I need to make it so I can download wirelessly since the receiver of the project lives in a different country
For IOS you need an actual chip that supports it I believe
I remember not being able to build a MAUI app because of this exact thing
chip?
I don't have too much knowledge on the matter so I might be wrong
An actual Mac is required to compile it in my case, but I have tried looking it up and I can't find it anywhere
You can try compiling for IOS and share the error you might get from it?
I have both a mac and an iphone and I can build and run it perfectly
the problem is I want someone cross country to play it
on android it is possible with apk
how to make someone with an iphone play it cross country
I can only think of this https://developer.apple.com/testflight/
But I think this might need a paid dev account to work at least I havent tried without one
Then again its been a few years since I did ios dev
It doesnt need to be published on the app store
But it needs to have a page on there therefore it needs an application doesn't it?
no
the entire point of Testflight is that people can test the app before it's published
but you do need the developer account which is $100/year
I dont think you can build a “apk” equivalent for ios and send that
oh that is a dealbreaker
thank for the advice anyways
This is sad
Build it for webgl and host it somewhere free
Then he can play it on ios from the browser maybe
@grave cape you can build special app packages for iOS. But for this you need to have a dev account, maybe even a enterprise one, not sure with that. And you need the device IDs of each user that wants to install. You can also distribute it wired of course, but thats just for local installations for example.
Include the wall's layer in the layermask
Otherwise it will be ignored
You have it backwards I think
If you dont include the wall layer in the mask, the cast will ignore the walls existance
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
hi, i'd like to know if there is a way to get the forward/right vector etc... in world space from an object that is child of another transform, because for now if i rotate the "Pivot" that is the parent object, the child object rotates but it's rotation coords are always the same (0,0,0), so when i try transform.right on the child object, even if the parent rotates it's always stays the same.
I mean, if the boxcast hits a wall, dont attack anything
Only attack if it hits the player
// NotSupportedException: Specified method is not supported.
// System.RuntimeType..ctor () (at <0da48681ced7494d83ae6a612d2206fc>:0)```Moved everything to new lines. Same error, no trace. Also used Array.ConvertAll after
can you show the full code, cant find the original one
It returns a Raycasthit2d
It has all the data you need
You can check if it hit anything by checking if the collider is null
CompareTag for example could help
return true in the if-statement.
return false if it fails (after the if-statement).
Your method is abool but you return a hit
return hit.collider != null && yourTagThing;
Yeah you should do the null check on the hit.collider ^
return hit?.collider.gameObject.CompareTag("Player") ?? false;
This will ensure the script returns false if nothing was found (and hit will be null)
No need for an if-statement
hit? returns null, and ?? false will then be called
Other than that, normal boolean checking with CompareTag
Maybe you should continue your questions in #💻┃code-beginner
My project is so complex and so interconnected, it would be impossible to show the full code. The trace points to a line but I don't think the problem is even there. I was hoping for some undocumented piece of knowledge might explain what's happening. I ended up commiting the current state, reverting to the previous commit (4 days ago) and will go piece by piece trying to figure out what happened. Thanks anyway
Yeah because its a struct
Oh, right, because it's a value type
I would just do this^
You could do return hit != default && hit.collider.gameObject.CompareTag("Player");
A struct cannot be null
hit.collider is not a struct. Wake up
Youre the one null checking a struct
Because just correcting in a normal way is probably too hard for you 😆
Twentacle's answer was fine, idk why over complicate it
Because I did not realise Boxcast in this case will return a RaycastHit2D with an empty collider
Basically
return hit.collider != null && hit.collider.CompareTag("Player");```
Yeah 2D queries are a bit different in that sense
return hit.collider?.gameObject.CompareTag("Player") ?? false;
I altered my previous answer by instead checking collider. This will work for you.
I have lines of code to write characters in TMP input field like this
hourIF.ActivateInputField();
hourIF.ProcessEvent(Event.KeyboardEvent("9"));
hourIF.ForceLabelUpdate();
hourIF.DeactivateInputField();
but it doesn't work. It works if it's alphabet like hourIF.ProcessEvent(Event.KeyboardEvent("t")); . why is that?
Ive also read that ?. (null-conditional operator ?) shouldnt be used with anything inheriting from UnityEngine.Object
Though im not sure
How can they mess that up?
It had something to do with the "fake null" that Unity has
I think null and ? aren't the same because Unity somehow has overridden null
Yeah that
Like a destroyed/missing component
Yeah that
I just generally avoid it so I don't use it with UnityEngine.Object accidentally
Here's a good explantion of it by Unity staff itself: https://blog.unity.com/technology/custom-operator-should-we-keep-it
It's a bit old but I think it still does hold up
And I got that from this article
https://nosuchstudio.medium.com/why-are-null-coalescing-operators-evil-in-unity-16f5a88d6071
Are you sure the player has the tag "Player"?
You should make sure hit.collider returns anything, and if it has the Player tag.
Because the code is fine
Make sure youre not mixing up layer name and tag
Is the max distance 0?
Paste code correctly next time btw. I can barely read that, even the full size image
Is the max distance supposed to be 0?
@slender moon My bad
Didnt realize theres an angle parameter
You can always put some Debug.Logs to see what object its hitting, and what layer and tag it has
Other than that, the code looks ok, so can't say much
If the player has children with colliders, make sure those have the "Player" tag too
And correct layer
don't put Debug after return, it exits the method at this point
Hey, is having a lot of event listeners too expensive for a webgl build?
I keep getting memory access out of bounds inconsistently when loading additive scenes
Hi developers
i am facing this issue and unable to find solution. Anyone have any idea about this?
Vertx made a debugging tool for visualizations of shapes: https://github.com/vertxxyz/Vertx.Debugging
Maybe you can use that.
It has examples, open them up?
Also, how is adding a single line in the package manager hard?
Hello! I am using Unity IAP and want to implement Promotional Offers for auto-renewable subscriptions for the Apple App Store.
I have a signed signature from the server for the promotional offer and I can't for the life of me find documentation for Unity IAP for a method that I can invoke to present the offer/trigger the Apple App Store payment flow. Anyone have an idea?
What part of the installation guide you don't understand? 🤔
It would have probably given you a choice if you only had to do one
First section adds the registery that contains the package, second section actually adds the package locally
Hey
How can I avoid looping over all gameobjects with tag (FindGameObjectsWithTag) when selecting an area with mouse?
What if I have 3000 gameobjects with tag and I'm selecting just a few?
Just raycast with your mouse and check if what you hit has the Selectable tag.
is there a box raycast? because im selecting an area not 1