#š»ācode-beginner
1 messages Ā· Page 301 of 1
you'd need to update it in the update, probably inside that if to avoid dumb calculations
that would only work with a singlepoint though, if you want the whole circle you might need to do rect type overlap using math with rect sizes.
I think you can also check if bounds intersect ?
so getting closer, but not quite yet!
single point is fine
its easier that way so i can avoid doing annoying code if its overlapping two things
how can i do a raycast?
i know normal raycasts but is it different for UI?
~~https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.EventSystem.RaycastAll.html~~
oh wait that circle is not a pointer right?
how are u moving the cursor via transforms?
guys plsssssss help
this whole day i have been through this problem and i still dont know what the cause is
its so confusing and absurd
anyone?
yeah lmao
circle is being moved like this
if (_playerInputController != null)
{
_transform.position += (Vector3)_playerInputController.markerMove * (speed * Time.deltaTime);
}
maybe you can try
[SerializeField] GraphicRaycaster gRaycaster;
[SerializeField] EventSystem es;
PointerEventData pointerData;
void Update()
{
pointerData = new PointerEventData(es);
pointerData.position = theCursor.position;
List<RaycastResult> results = new ();
gRaycaster.Raycast(pointerData, results);
if (results.Count > 0) Debug.Log("Hit " + results[0].gameObject.name);
}```
how can i debug stuff like this
this will funnily enough distance the camera by -1 on each Update (so many many times a second), you might have confused transfom.position with player.position. Or just drop it and use -1f if you know the camera is not going anywhere in the z direction
lol
can i open a furom for this problem because it seems to be a very long and complex one
also, using a constant in the third parameter won't do you any good, read the doc page i sent before and it will explain it nicely
pls bro how do i start playing an animation at its end?
like what
this makes the marker need a canvas as a dependency of the graphics raycaster though, is that fine?
This?
ur cursor /boxes are not a UI element?
my game when i jump it swaps the tile and disables the box collider, in the build it doesnt swap the tile but disables the box collider how can i debug what is happening with the tiles
this
What is the code that runs when you jump
the cursor is a UI element yes, but it appears to need a canvas on it?
the most common approach is having some speed variable and multiplying Time.Timedelta by it as the third param
if(RedOn)
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = true;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = false;
RedTile.SwapTile(TileGrid,Tile);
BlueTile.SwapTile(Tile,TileGrid);
Debug.Log("RedOn");
}
else
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = false;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = true;
RedTile.SwapTile(Tile,TileGrid);
BlueTile.SwapTile(TileGrid,Tile);
Debug.Log("RedOff");
}
having a constant like 0.001f results in the camera staying in that in-between point of 2 positions specified
oh
and you want it to eventually reach the target (player)
yup, docs are really great give them a shot!
u dont need a canvas per UI element, as long as they're all in the same canvas or reference the correct graphic raycaster canvas
So which one is the one that should be happening? And why do you have so many get components instead of actually having those already cached
okay thanks
i will fix the getcomponenets but wdym which should be happening
if (Input.GetButtonUp("Jump"))
{
if(RedOn)
{
RedOn = false;
}
else
{
RedOn = true;
}
}
Well, you have two conditions here. Which one should be happening, and what is actually happening
i pass in normalized time (being 1), the animation has loop set off, yet it still plays the beginning, what did i do wrong?
this is as simple as RedOn=!RedOn; a toggle basically
no clue what the issue is, just letting you know š
so i dont need that else
they are both working but the tile isnt swapping
its a problem in the tile swapping
but i think you have a point in the getcomponenet
so i will quickly fix that
the entire if statement here can be simplified to RedOn = !RedOn.
really getting annoyed at this error while trying to build an android app ```Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
FAILURE: Build failed with an exception.
- What went wrong:
Could not determine the dependencies of task ':unityLibrary:mobilenotifications.androidlib:compileReleaseJavaWithJavac'.
Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-33 Android SDK Platform 33
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
Using Android SDK: C:\Program Files\Unity\Hub\Editor\2022.3.24f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK
-
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. -
Get more help at https://help.gradle.org
BUILD FAILED in 7s```
red wiggly line things appeared
you define the RedTile and BlueTile variables in the context of a Start() function, hence after it ends they are forever forgotten
Make them class variables just like you have BlueGrid
Local vs global scope
make sure to have them defined in the class-scope (outside any function) and assign their reference in the start() function.
Could you theoretically store all static variables in one class and there wouldnāt be an issue with that?
Nah. Make it a class variable, like RedGrid and BlueGrid are
Like does it really change anything based on what class you store a static variable in?
yup, basically how singletons work. static refernce to an instance and public variables to access them
ok i will do that
Cool
but, this is, to say the least, very naughty
Yeah, it seems like it would be very disorganized
yeah, nice for quick prototyping, but will bite you in the ass when you need to split it according to actual needs and responsibities 
Yeah, the only DontDestroyOnLoad singleton I have handles player connections, Iām planning on making another thatāll handle the pause menu
Speaking of which, for a pause menu, should I make it a separate scene that I load additively on a prefab that I instantiate?
Golden rule i follow is to not solve issues that don't exist yet, so avoid making the absolute dirtiest solutions, but also don't create a rainbow highway for 1 horse
Thatās a good philosophy, I tend to make rainbow highways for one horse, I should really stop doing that
oh right, we all sometimes go into the rabbit hole of "I could probably make is much better and expandable... and drop and use... and efficient... and", and a few weeks later I scrap the idea/the team decides it's not really needed. As human as it can be hahah
Exactly lol
but hey, this might be a cool tool to sell on the marketplace for a quick buck someday
why cant the build be a good boy and copy the editor
how do i get this ui text to be on the game screen?
Looks like the UI is positioned to the side of the bottom right of the canvas?
oh so it has to be in that canvas to show up
an overlay canvas doesn't really exist in the game world
press F with the canvas selected to focus your view on it
each pixel on the canvas is one unit in the scene view
so it's very big
Rather than positioning the ui by hand, set up the anchors first
You can find guides pinned in #š²āui-ux (where this question belongs, just for next time)
for example, if the element should be in the top left corner, pick this anchor preset
this will let you position the element relative to that corner
so as the screen size changes, it moves around correctly
anyone?
Have you tried in #šāanimation ?
I am terrible with animations, so I don't know, sorry
What happens if you play at different normalized times?
I forget if Play() does any cross-fading
I wonder if you're just seeing the animation blend
still plays at beginning
Set the state to 0x speed and see how it looks
hmm let me look
do u mean when you click on the transition arrow between animation in animator window and a thing shows up
This wouldn't be a transition in the animator controller -- Play() doesn't use those
I just can't remember if Play() does a little crossfade
wouldnt that be this guys thing
but maybe i can use crossfade and set the fade speed or wtv to 0
i'm struggling to parse this part of the docs
If the transition from one state switches to another, it may or may not be blended. If the transition starts at 0.75 it will be blended with the other state. If no transition is set up then Play will continue to 1.0 with no changes.
i would try a 0-duration crossfade, yeah
may or may not
š ā
I haven't used the animator much recently so I don't have practical experience here
documentation moment
hey guys, im new to Unity and I was wondering why this code isnt working, i keep getting the error: NullReferenceException: Object reference not set to an instance of an object. Any help is apriciated, manny thanks :)
{
public const int PlayerHealth = 50;
public PlayerCls Player1 = new PlayerCls(PlayerHealth);
public PlayerCls Player2 = new PlayerCls(PlayerHealth);
public UI ui;
void Start()
{
Player1.Health--;
ui = new UI(Player1, Player2);
}
// Update is called once per frame
void Update()
{
}
public void OnHit()
{
print("Hit");
}
public void OnStand()
{
print("Stand");
}
}```
```public class UI : MonoBehaviour
{
public Text Player1Health;
public Text Player1Points;
public Text Player1Hand;
public Text Player2Health;
public Text Player2Points;
public Text Player2Hand;
public Text Nararator;
public PlayerCls Player1;
public PlayerCls Player2;
public UI(PlayerCls player1, PlayerCls player2)
{
Player1 = player1;
Player2 = player2;
}
private void Start()
{
Player1Health.text = "asd";
print(Player1.Health);
//Player1Health.text = (Player1.Health).ToString();
}
private void Update()
{
// UI_UpdatePlayerHealth();
}
public void UI_UpdatePlayerHealth()
{
// Player1Health.text = (Player1.Health).ToString();
}
}```
use https://gdl.space/ to post ur code
š
also it means u r using a variable that you havent assigned
okay :)
print(Player1.Health);
Print is using when coding in unity?
it usuarly works
if you want text to show up
as ui
you create an object in ur scene that is of the type text
so Text myText
then you change it by myText.text = "text here"
thats declaring not assigning
this?
this is assigning
well check which line the error is
but there still might be one missing
if its assigned then you have a copy with it unassigned
a private variable that u maybe missed
instead of guessing look at the line number of error
yes i know why its being caused, but i dont know exsactly for what reason it is being caused
i made a construcor in my calss, but after i initialise it the value is not asssignet / stays null
dam didnt work tho
why do you have a constructor ?
monobehaviour should not have constructors
because i want to get a diffrent object that I have in my main function / game loop
or am i doing it wrong
you use instantiate
yeah this is all sort s of wrong
if i understood correctly
i only learned c# up to this point so i dont know hihi
oh i thought he said create a different object
this is specific to Unity, normally this would be ok but unity overrides the regular behavior for class
hmm. what is best practice to do then?
You can still do it on regular classes, just not ones that inherit Object
assign everything in the inspector when possible
{
Vector3 directionToTarget = (_blackBoard.TargetPos - _turretPivot.position).normalized;
Quaternion newRot = Quaternion.Slerp(_currentRotation, Quaternion.LookRotation(directionToTarget), (_state == State.Default ? _lookAtRotationSharpness : _shootingRotationSharpness) * Time.deltaTime);
_turretPivot.rotation = newRot;
_currentRotation = _turretPivot.rotation;
}```
At a glance what am I doing wrong here? I just need the object to look at the target. However, it's stopping when its looking to the side. I made sure that the model's forward is indeed on the Z axis when moving it
Whats currently happening is this, its stopping on the side
it it local or global? make sure select the global and check the direction
thanks checking now
Its global
Same result, however I do notice something strange if this matters. When I move the pivot forward, the X axis changes instead of the Z
the z is the side that looking to the player, right?
so thats the forward of the object it self
you can change it with a 3D software like blender or easily add or subtract 90 to the direction before applying it
I see, how do I fix this? I can't really change the model
Got it
I also noticed this in the original script, since I didnt understand what it did I edited it out
Not sure if its useful or not
So what I need to do is create a variable called aimoffset and work off that
yes and add it after the Quaternion.LookRotation(directionToTarget)
is that a vector 3 or float?
v3
not sure if it will work
doesnt seem to be working
I guess you should change the script a bit
When you said add it after Quaternion.LookRotation(directionToTarget) do you mean adjust the transform after its applied?
I created an empty gameobject inside it and parented the pivot, rotated the parent to 90 degrees and it seems to fix it
that's another way to fix it of course
btw what I mean was that where you write Quaternion.LookRotation(directionToTarget) inside the Slerp
write Quaternion.LookRotation(directionToTarget) * Quaternion.Euler(_pivotAimOffset) instead
the _pivotAimOffset will be a Vector3 offset in any direction you want
Its working now so whenever I want to do offsets I need to convert it to quaternion then multiply it?
I'm trying to make it so that if you're pressing the sprint key and you aren't in throwing mode, it sends a message that says running. However, for some reason it just floods the console with the message indiscriminantly, regardless of if I'm even touching my keyboard. This seems so simple, how is this happening?
{
MyInput();
SpeedControl();
if(Input.GetKeyDown(sprint) && throwObject.GetComponent<ThrowManager>().readyToThrow == false);
{
Debug.Log("Running!");
}
}```
there is multiple ways to work with angles but I think this is best suited for your code
just create a vector3 and multiply with Quaternion.LookRotation(directionToTarget)
oh jesus christ LMAO
Its great thanks. I have another question in regards to using this though. Before I would calculate if a transform is facing another via if currentAngle < targetAngle. However, with this code the transform is no longer accurate in game. How would I be able to get the simulated transform.forward with the offset. I could just use transform.right to compensate too
public static float GetAngle(this Transform source, Vector3 pos, bool ignoreY = true)
{
Vector3 dir = pos - source.position;
Vector3 forward = source.forward;
if (ignoreY)
{
dir.y = 0f;
forward.y = 0f;
}
float angle = Vector3.Angle(dir, forward);
return angle;
}```
sorry didn't get your question
So basically, I want the turret to shoot when its facing the player. The code above is to get the angle from its forward position to the target. However, now that I'm using an offset to calculate when to stop the rotation the angle is innaccurate. Is there a way to somehow get the transform.forward with the applied offset?
Right well, its getting the angle but instead of 0 its 90. It might be as simple as doing -90 or checking the distance between the target angle and current\
I don't know the whole context, but why isn't forward corresponding to the object forward..?
The model forward is actually its side
you can use vector3.dot maybe
Its from unitys microFPS project and its an FBX
I could actually fix it in blender because its not rigged
Then fix it.
Or at least parent it to an empty and adjust the rotation such that the parent is facing correctly
It does seem more simple to fix it I figure I could learn something by fixing it with code.
No one does that
It's like adapting for incorrect way of doing things
You should fix the underlying cause instead of making workarounds
btw if you export the fbx file over the file which is in unity it will automatically change it in game too
so you won't need to assign anything again
The code logic shouldn't cover for asset issues. That's a sure way to get more issues.
ok I fixed it its not perfect but it gets the job done.
how would I go about creating an npc which is interactable but has tree decisions?
2d btw
use something like ink probably
Cheers I'll take a look at what that is
Sorry just a quick question but do you know if you're able to have specific follow up choices based on the choice you made using ink?
yes
does raw image or image require a canvas?
Yes
so a sprite renderer is required for ingame
They're all 'in game'
sorry, in world
If you mean the world, then not really. You can have world space canvases too.
like using textmeshpro
not ugui
can things on canvases respond to colliders with a rigidbody
basically im making item labels above items on the ground and I want them to collide so none are overlapping
TMPro has both world and canvas versions.
That doesn't make sense
You can put colliders and rigibodies on any object, if your canvas is achild of that, it will "move" with the object
(assuming it's a worldspace canvas)
i was imaging everything would be on the same object, but now I guess it makes sense for them each to be different canvases
so dumb question but i just started unity a couple hours ago and i got fps movement and everything working but colliders are just not and im unsure of what to do
Do you have the isTrigger setting enabled? That makes them non-physical.
Other potential issue is: are you moving by doing transform.position = ? That ignores collisions and may make you pass through colliders
yep that does seem to be the problem
ill have to find a new movement controller to use and maybe thatll fix
I have tried about 10 different ways but I can't seem to figure out this Quaternion. I'm trying to instantiate a prefab (a fireball). I've got it spawning at the player location, but I'm trying to get the rotation of the fireball to match that of the player. everything i tried it either locks at 0 or 180. https://paste.ofcode.org/Eq9YArGd95ZVr86JK3xdgG
I have what I guess is a security question. I believe this should be the right place to post. If I am writing saves to a JSON format, is this a major security risk? I don't care about people adding in items and stuff. I just ideally don't want files that look like saves to ruin people's computers if they download them and then use the game to load them.
Simply don't use quaternions. Use euler angles
Also, don't use Find, and cache your references when you get them
Can anyone see an issue with this code, it would work prior to me adding the float and if statement. If more code is required to understand please let me know
if theres an issue, then say so. people arent gonna guess at whats wrong
anyone have a suggestion on how to better handle item labels? right now i just have rigidbodies and colliders on them so they do not overlap, however when many stack, they all kind of push away slowly and it ends up looking bad. Is there anyway make them "push" more or is there a better alternative to this since I imagine its intensive for no reason
the issue is that the pathfinding would work prior to me adding the if statment and float
add a debug and see if the code is even running, if it ever enters the if statement
I was trying to make it so it would only work when the player is within it's radius
alr
yeah nah it ain't running it
I've played games that didnt even bother doing anything about this case because they didnt have so many items. Do you really need this many or is this just a test?
I think your only real solution would be hiding the names of objects that are underneath. Maybe allow right clicking to get all objects under an area
Doesn't Diablo have a thing that filters bad items and doesn't show them?
just a test but if you've ever played POE, diablo or Grim dawn, thats the system im going for
i don't want to hide anything
What debug did you write, and what values did it show?
just Debug.Log("word");
and it showed nothing
It's been awhile since I've played diablo, but you're gonna have to hide something otherwise the entire screen will be full of item labels
Oh. No, that won't help at all
ah
debug the actual values
yes thats the point
what is distance
i do not want to hide anything
distance between the player and enemy
obviously there will be loot filters
I meant debug what the distance is.
this is the goal
but for them to resolve instantly
not slowly push eachother away
okay looking into this now, thank you
says 16 when ran
could the issue be that I did this in start rather than update
Ok, so it is greater than 5. You will not update the path
Well. It depends, do you want it to only happen one time in the entire life of the script, or to check every frame?
Start does the former, update does the latter
Also, you like want to update the path when OVER 5 units distance, right?
Right now you only do when UNDER 5 units
nah under, when the player gets within the enemy's radius I want it to start chasing the player
Ah ok. Fair enough. just making sure
maybe I did the area a tad small
It is pretty close. But I understand the logic now. Make it a variable and just play with it until it feels right
You blasphemer
How dare you suggest that in my presence
Thanks for the help man really appreciate the guiding rather than straight up telling me the possible solution
ah, if thats the goal then you'll not be able to rely on unity physics at all. I havent done anything similar but i believe a relevant topic is aabb test
yeah i assumed physics isnt the best idea but was the easiest to setup. How would I go about implementing that though? should I have all of the labels on the same canvas and when they are spawned, do that check to make sure they are in a empty spot?
im not really sure of the best implementation here. i assume you would be using Bounds and need to keep track of the UI currently on screen. then trying to find a free space from there
there is https://docs.unity3d.com/ScriptReference/RectTransformUtility.CalculateRelativeRectTransformBounds.html
which also has a typo
Transfdorm
hm, maybe i just keep the physics implementation for now, its not too bad when theres a few items
there is no way to make the rbs "push" faster?
like basically increase their timescale
having rb on UI is definitely questionable
sure but it works
@summer stump sorry to bother you again but I kinda created a new issue where I can't seem to figure out how to slow the enemy down
I just made crappy movement!
"works" but its not customizable really. Maybe you can use this to do your own depenetration
https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
yeah, thank you
I think a good choice there, using what you have, is to turn that 3 into a variable, perhaps currentSpeed. Then have a maxSpeed variable. When you get close to the end, subtract from your current speed until it's 0. When starting a path, add to it until it's max speed
can you not cast a collider2d as a "collider" apparently this function can't be used for 2d?
I'll give that a shot cheers
You have two translate calls in PlayerControllerX
You only update rotation of the propeller in Start
I find both of those things interesting, but likely not the issue
Perhaps i shouldnt have made a new script for the propeller xD
Perhaps. Try removing it.
Your video didn't show the hierarchy clearly. Is the propeller a direct child of the Player object?
I did see the Player is scaled down to .5, but at least it was uniform. If there is a child between that and the propeller that is NOT scaled uniformly, that could definitely cause this issue
there is no more employ gameobject between player and propeller
Well can you do a screenshot of the whole editor, with the propellor selected?
I have a string with the name of one of my item prefabs in it, the string comes from my back-end
What's the cleanest way to access the prefab's fields (sprite) with only the name in a string available?
I have this:
itemDrop.GetComponent<SpriteRenderer>().sprite = Currencies.Instance.Wood.Sprite;```
The problem here is that I need to write one of these lines for every item in my game that can drop.
Perhaps a dictionary with the name as a key? The sprite would be the value. If dictionary has key, itemDrop's sprite would be set to the value
Then the only change you would need to make when adding a new item type is to add it to the dictionary without misspelling it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
public float constantFlyingSpeed;
public float rotationSpeed;
public float verticalInput;
public float planeTurningSpeed;
public GameObject propeller;
private float propellerRotationSpeed = 10;
void Start()
{
}
void FixedUpdate()
{
verticalInput = Input.GetAxis("Horizontal");
//this just flies forward like normal
transform.Translate(Vector3.forward * constantFlyingSpeed);
transform.Translate(new Vector3(0, verticalInput, 0));
transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));
transform.Rotate(new Vector3(0, 0, propellerRotationSpeed));
}
}
whats the error?
You have compile errors there
I know
Also, screenshots would be better, as requested
ok Ill do both
Well, to help with that error (which should be your #1 priority), it would help to know which line is line 30
Anyway here's a shortie from the actual gameplay
I assigned propeller here so now there's no error
at first it worked very well
but as I moved forward i completelly somehow kinda fucked it all up
and gradually got worse and more complicated š
But this is from the unity's official tutorial
You are rotating around z every frame in your code
The second rotate call in FixedUpdate
im following the assigenments they got there
ok good notice
Ill change that
At list now I dont got the weird random spins
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
public float constantFlyingSpeed;
public float rotationSpeed;
public float verticalInput;
public float planeTurningSpeed;
public GameObject propeller;
private float propellerRotationSpeed = 10;
void Start()
{
}
void FixedUpdate()
{
verticalInput = Input.GetAxis("Horizontal");
//this just flies forward like normal
transform.Translate(Vector3.forward * constantFlyingSpeed);
transform.Translate(new Vector3(0, verticalInput, 0));
transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));
transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));
}
}
now my question is.... how do i get to move the actual propeller lol
the goal is to move the plane up and down
while giving it rotation
and i tried to rotate it around game object placed on its nose
to look as if the propeller is doing the hard work
but couldn't do that because I had soooooo many random weird things breaking apart once i tried that
so I changed my mind and im like ok sure Ill keep rotating the plane around its center.
Guys I'm creating an open world wild west game, right now I'm learning how to create basic fps controller because I'm new to the coding stuff when I'll be creating my proper 3rd controller for the game should I use animated controller like walk run idle animations or will I have to create something Procedurally generated I want to create a controller which can slide and have other good ragdoll effects like rdr1 or rdr2 so what should I do, I don't know much about animation and rigging other than unity animation controller basic stuff basically. Guide me on the right path so I don't regret it later
whats the best way to stop groups of enemies from grouping up and stuff
Something like this https://github.com/PathPlanning/ORCA-algorithm#
This is a extremely complicated topic. Rockstars animation system is a complex combination of motion matching, advanced Ik rigs and this master thesis of a danish guy that also worked in unity https://runevision.com/tech/locomotion/
To make the controller feel realistic and not too comolex
Does unity support custom asset ?
Please help me man
U can import any type of file in unity
Bro I don't know anything about realistic third person controllers
what
I just wanted to ask does having cubes as buildings cause performance issues?
Someone told me it can cause performance issues
Bro it's increases performance
Who told you that
So can I make to work with scripting
A guy was helping me build my game. He knows a crap ton I mean he helped me in everything
What are you asking?
What type of file are you trying import ? And make it work with scripting ?
No. that makes no sense even. Primitives will always have better performance than complex meshes. Either you misunderstood the person or they know very little
Even rockstar games uses cube as buildings for higher level Lod's
oh ok thank you! can someone call me I need to list my problems I am facing
I will not. Very unlikely anyone else will. Just ask one question at a time
I ned to call for it
Well, good luck. EXTREMELY unlikely anyone is gonna do that
Cube has only 12 triangles while a building has thousands
There is no easy way to make a realistic controller.
I guess you're right there is no shortcut in life
So I should use this danish guy system ?
You can try but itās not easy to use. In fact it does not work at all in modern unity
Bro what do I do then build my own ?
We have been working on it and incorporating it into our motion matching system. So far it has taken 3 developers a total of 8 months to get it to a working state
Oh man this thing sound way more complex than I thought
3 devs that I assume already had extensive knowledge in programming and animation
Start with something less complicated. Perhaps a simple animation controller with a 2d blend tree for the locomotion
Should I just create an animated controller then ?
Programming yes, animation not so much
2d blend tree whats that
Fair enough haha.
Right now I have created a basic controller but it's moving in global axis if my controller is looking the other side and I press W it will go right or whatever the global direction is instead of moving forward even though in transform it's transform.localposition
Localposition would have no affect on that...
Use transform.forward
Ok
Not any common file it's my own format
It has embedded texture
your own ? š
Yes
i don't think it will why don't you import it ?
no I'm asking will unity support to read such files in game
Then it may not be compatible. You can't just import any file format and expect it to work.
You can google supported file formats
I know buddy that's why I'm looking if I cann make it work with scripting
I just don't want to expose the textures are .jpg and .BMP files
Really can't answer with the 0 details we have. But probably, via conversion to some other format
Not really a beginner question
why don't you use the normal formats ?
Ah. No matter what format you use, they will still be able to do that
bro don't care too much about that make a great game
If the data is on their computer, they can decompile it
we indie devs can't make great games if we focus too much on side quests
focus on the main quest
Agree
Agree +2 if anyhow I use the custom format still it might be loaded in the memory
you're priority should be
-
player controller
-
Enemy or AI System
-
The World or Environment
-
in Game Events
-
some sort of idk property or shop system
-
Inventory
-
maybe a car or horse controller idk in which time you're game is set
-
UI
- amazing Missions that feels unique
I missed the part where flappy bird had all of that
we are talking about serious games here š¤£
not some mobile garbage even tough im creating a mobile game
Hello, i encountered a problem in my C# code saying me this :
Assets\Codes\Gestionmap.cs(64,33): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
The error occurs in this line :
int z = (int)Math.Round(biome.k + biome.amp * (Math.Cos(2 * Math.PI / 10 * biome.fx * x) + Math.Cos(2 * Math.PI / 10 * biome.fy * y)));
Someone know how to solve this ?
I think the problem is link with the Math librairy
Hello, in the dot product doc : https://docs.unity3d.com/ScriptReference/Vector3.Dot.html, why don't they directly use transform.forward ?
Instead, they use transform.TransformDirection(Vector3.forward);
What's the difference ?
Most likely. Why not use Mathf?
guys my character is moving in global axis instead of local even tough im using transform.localposition and transform.forward just doesn't do anything the characters stops moving. i need help
btw my character does rotate in camera direction
No difference. The docs sometimes have quite the quirky examples, so you shouldn't rely on the examples completely.
Use you own judgment and the actual API explanation.
Well, you're probably mixing up local and world positions/direction. Hard to say without seeing the code.
!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.
the ` `` cs thing is not working for me i can't send
Upload to a paste site then
using System.Collections;
using System.Collections.Generic;
using UnityEngine
;
using Unity.IO;
using UnityEngine.Accessibility;
using UnityEngine.Scripting;
using Unity.Multiplayer.Tools.NetStatsMonitor;
using Unity.VisualScripting;
using UnityEngine.Animations;
public class ThirdPersonControllerScript : MonoBehaviour
{
private Vector3 location;
[SerializeField] private int Speed;
[SerializeField] private Animator Animation;
private void Update()
{
// W FORWARD
if (Input.GetKey(KeyCode.W))
{
location.z += Speed;
transform.localPosition+= location * Time.deltaTime;
Animation.Play("walking");
location = location.normalized;
}
// S BACKWARD
if (Input.GetKey(KeyCode.S))
{
location.z -= Speed;
transform.localPosition += location * Time.deltaTime;
transform.rotation = transform.localRotation;
Animation.Play("walking");
location = location.normalized;
}
// A RIGHT
if (Input.GetKey(KeyCode.A))
{
location.x -= Speed;
transform.localPosition+= location * Time.deltaTime;
transform.rotation = transform.localRotation;
Animation.Play("walking");
location = location.normalized;
}
// D LEFT
if (Input.GetKey(KeyCode.D))
{
location.x += Speed;
transform.localPosition += location * Time.deltaTime;
transform.rotation = transform.localRotation ;
Animation_.Play("walking");
location = location.normalized;
}
}
}
ok now its working
hahaha
thank for the help, a last error occurs at the end of my code, and i dont understand how to fix that..
MissingMethodException: Constructor on type 'Gestionmap+Plaine' not found
But my class Plaine is defined like that :
public class Plaine
{
public int k = 80;
public int amp = 4;
public double fx = 0.2;
public double fy = 0.2;
public int surface = 1;
public double p_tree = 0.002;
public int x { get; set; }
public int y { get; set; }
public double p_structure = 0.01;
public int[] structures = new int[0];
public int[] caves = new int[0];
public double p_cave = 0.01;
public Plaine()
{
}
}
And the line of the error is this :
object biomeInstance = Activator.CreateInstance(type, x, y);
Someone knows what to do ?
You don't want to use local position. That will disregard the object rotation.
Set transform position.
transform.position ?
so basically im making a game called "BUCKET" but i dont know what to do with it ive already gotten the movement and the first person any sugggestions?
also if u want the movement i have it
still the same dlich
Yes. Although, you'll need to transform your movement direction or use a world space direction like transform.forward. or use Translate.
Ideally, go through the beginner pathways on unity learn as this kind of basics are all covered.
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
im also using a camera wonder if thats causing the problem
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.IO;
public class ThirdPersonCamera : MonoBehaviour
{
[SerializeField] float SensY;
[SerializeField] float SensX;
[SerializeField] private Transform PlayerRotation;
private void Start()
{
// locked the cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float MouseX=Input.GetAxisRaw("Mouse X") * SensX * Time.deltaTime ; // Get X axis
float MouseY = Input.GetAxisRaw("Mouse Y") *-1 *SensY *Time.deltaTime ; // Get Y Axis
PlayerRotation.localEulerAngles += new Vector3(MouseY,MouseX,0);
Debug.Log(MouseY);
Debug.Log(MouseX);
}
}
Take a screenshot of the error including it's details.
Don't cross post. If you're looking for ideas, #archived-game-design is the appropriate channel.
you can read this ? the screenshot is tiny haha
Share the code of Gestionmap
It's fine. You can click and zoom into it.
Ah, you shared the line of the error
What's Activator?
object biomeInstance = Activator.CreateInstance(type, x, y);
a way to create some instances i think
[System.Obsolete]
private void OnCollisionEnter2D(Collision2D collision)
{
print("og");
boomerangRain.gravityModifier = -0.73f;
}```
thats the only solution i found to create instances of different classes
its not working
boomerangRain is particlesystem
you can create instance by its class constructor
no idea why you use Activator, overkill
Ah, the C# activator. I'd really avoid using it though
Okay, so what are you using ?
Thanks a lot for the answer!
because i have different classes
the variable type can refer to a lot of different classes
Hard to say without knowing the co text of where you're using it.
Also, the error is probably due to incorrectly using the Activator. I don't see a constructor that takes 2 parameters.
i have a dictionnary of types, and the aim of this line is to take one of this types, and create an instance of it right after
foreach (string biomeType in typesTab)
{
int x = rand.Next(0, n);
int y = rand.Next(0, n);
Type type = biomes[biomeType];
object biomeInstance = typeof(type)(x, y);
biomesTab.Add(biomeInstance);
}
return biomesTab;
Why are you using types? Where do you define them?
thats just that
can someone check this please
Dictionary<string, Type> biomes = new Dictionary<string, Type>();
biomes.Add("Plaine", typeof(Plaine));
biomes.Add("Foret", typeof(Foret));
function isnt working
i want to refer all my types in that dictionnary
I'd use scriptable objects instead. Or some for of the factory pattern.
Instead of hardcoding your types biomes like that
okay but i need the constructors because a tuple (x,y) needs to be passed when i create the instances
so i make a dictionnary of objects ?
Dictionary of SOs or objects of each biome type/factory of that type.
enum+ switch case to create instance and return the reference to parent class
anyone got a good way to create an npc that has different response options depending one the your previous choice?
to prevent you misspell the class name and got key not found exception
i think all of this is ahead of my actual c# level haha
what you mean with SOs ?
Then activator is ahead of your level for sure as well.
ScriptableObject
hi someone please help! I made an animation but it doesn't show in unity play
public float calculateUnitTerminalVelocity()
{
float unitTerminalVelocity
= Mathf.Sqrt((2 * unitMass * gravitationalAcceleration)/(dragCoefficient * airDensity * crossSectionArea));
return unitTerminalVelocity;
}```
is it actually necessary to declare the public float unitTerminalVelocity above the calculation or it's fine not to?
Well you're declaring it twice there. Both outside and inside 'calculateUnitTerminalVelocity' so the public will get overwritten every time.
So I've read through this amazing article https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity
but was left wondering if I should use PascalCase or camelCase for private parameters, when I prefix them with an underscore, aswell as what you think / use / like better.
This
private int _Speed;
private bool _IsWalking;
or this
private int _speed;
private bool _isWalking;
as long as it consistent, though i prefer _camalCase since you can use _PascalCase fro private methods now.....
Don't cross-post.
Well I posted it in unity talk and then realized this is a code question and I should probably ask in a code related channel :)
š Note that you can delete messages or just indicate that the discussion has moved.
[SerializeField] private int _originalMaxEN = 100;```
I wrote this code but Unity doesn't display the numbers correctly (both showed up as zero), any reason why?
Well someone answered there so deleting the message would have no point.
I first went to #archived-code-general bcs they suggested I ask there, posted it, then deleted it bcs this is a rather beginner question and then asked here. You know I didn't spam it, it was reasonable to leave and post it here aswell.
Thanks for reminding me of the guidelines, but I don't think I really cross-posted.
It may initially show as zero but you can adjust the max HP and En as per your requirement in Unity Editor
I'm making an Offline RPG game in Unity. I want to save some things in my game. I have heard of two recording systems for this, one is PlayerPrefs and the other is to save in json format. PlayerPrefs is simple and easy to hack, and it does not work on all devices in json format. I do not consider the json format because it cannot be played on every device, and since the game is offline, I do not see any harm in doing it with PlayerPrefs. What do you think, what would be better for me to do?
Note that it is recommended to not write HP or EN, as I would not know what EN is for example
{
get { return _originalMaxHP; }
set { }
}
public int originalMaxEN //Allow access of the private integer OG Max EN
{
get { return _originalMaxHP; }
set { }
}```
I tried to extract the values into the editor panel but it doesn't work either
the integers OriginalMaxHP and OriginalMaxEN just don't show up entirely
what so the editor ignores the values i gave to private integers entirely?
Depending on the scale I guess. I don't remember the exact reason, but I've seen a video about issues with player prefs being static and needing to be used correctly. A game I recently made for the fish fest game jam had less than 10 values safed to player prefs and it worked fine. I don't know how well it works with ~100
Did you perhaps give it the 100 value after you put [SerializeField] ?
not sure what you mean
The deafult value is 0
If it was serialized before you did =100 the editor is simply doing its job and rembering the original default serialized value
Try hitting reset on your component and see if it changes to a 100
Or just adding the component to a new gameObject
Which one did you do? Player Prefs?
My bad, I missed the context in #š»āunity-talk which actually did indicate that the discussion had moved.
Yup. Player prefs are way easier to set up than all the json stuff
huh now that works, thanks
i still am unable to make the public version that uses an accessor to show up though
shouldn't the public accessor be visible on the editor?
!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.
oh ye sorry
You should try to make it more readable
I understand Thank you for your comment
it wasn't supposed to apparently
Accessor are not serializable. You put [SerializeField] on the private variable just for that
/die
Np, good to see
I think I saw a tarodev video how you can serialize them
There is no need to serialize them
JSON can be used on all platforms, especially Unity's JSON solutions. PlayerPref can become clumsy if you end up serializing a lot of different objects, but either one will work.
so the problem is that my Debug.DrawRay is not working as well as my Debug.Log can someone help me please?
It's all good, good to see this matter resolve rather quickly :)
The best way to do it like this
I ll try
// Looks like this then
It is easier to comment on code, when being able to copy and paste it
Since there are more than 50 pieces of information I want to save, then json is the most logical option.
First of all consider using
hit.collider.CompareTag("Interactable")
Since there are more than 50 pieces of information I want to save, then json is the most logical option.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Interaction : MonoBehaviour
{
public RawImage interactionImage;
void Start()
{
}
void Update()
{
RayCastShoot();
}
private void RayCastShoot()
{
RaycastHit hit;
Vector3 forward = transform.TransformDirection(Vector3.forward);
if(Physics.Raycast(transform.position, forward, out hit, 2.2f))
{
Debug.DrawRay(transform.position, forward * 10f, Color.green);
if (hit.collider.gameObject.tag == "Interactable")
{
Debug.Log("object that was hit: " + hit.collider.gameObject.tag);
interactionImage.enabled = true;
}
else interactionImage.enabled = false;
}
else Debug.DrawRay(transform.position, forward * 10f, Color.red);
}
}
Yes now this is good
ok, thx for showing me š
(If it gets any longer you can use !code to paste the code on the website and share the website link)
š 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.
Bcs it's not foldable and lorge code blocks obstruct the chat
I see, what is considered longer like more than 50 lines?
When you have to scroll to see other messages I'd say xD
Like this fills my 24" screen
got it, alright then š
First of all put the debug ray outside the condition, so you can check if it hits something, even if it doesn't*
Oh wait you do
oh ye the raycast(when its outside if (hit.collider.gameObject.tag == "Interactable") does register the tag)
Just do it regardless of if it does
Oh I see you want it red or green
Too fast to judge then, thats nice (if it works)
But you dont see the ray at all?
well the problem as of now is that I cant see the lines at all
yes exactly
try writing transform.forward
ok
Hello all. This is a little game i'm making. The red bvox on the left is the score for what you just played. As you play more turns, i want the scores to kind of log themselves on the screen, and eventually look like this. Obviously with the different values and numbers from each play and etc and alligned correctly, Should i do this with an array and list? And howso? Im very lost.
Do basic trouble shooting. Try displaying a simple ray. If that works, try to change the parameters to fit your needs
Should i instnatiate and move it down by a certain amoount everytime? or is their like some sort of fill in system i can use
Also disabling Gizmos in the scene view will make rays not be drawn
oh..., well thats embarrassing XD
ehm so ye, it works now, sort of...
You can have either one (List/Array) and when you enter this scene, have a script go over the list and set the text stuff to each element of the List/Array. Easiest way is to have 20 Text Objects, add them to another List, and for each entry in your score List/Array, you update the text value of the current text List/Array and set it to active
but nothing I cant resolve lol thx
Nah everyone does that when first working with unity, trust me xD
Reset the ray to forward
Instead of rather Instantiation?
yikes, well thanks š
transform.forward is just straight forward, not what you want probably
yep, will do
I mean what you like. If you want to instantiate, you would need to keep an array of positions where you instantiate it. It's way simpler to just make them in the scene view, disabling them and then activating them at runtime if needed
@lavish magnet (And don't forget to use a Layout Group)
Like this?
What is that?
The component being used for aligning ui objects
Wow I did NOT know that exists, but it's quite handy
Are you talking about layout group?
Well, did you use to align everything manually?
Yeah I anchored and positioned everything manually
Ive encounter a problem, where I am trying to pick up an item on the floor when I collide with it (still figuring out how to use interactive so im just starting from collision), and this error shows every time i hit the object:
NullReferenceException: Object reference not set to an instance of an object
Item.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Script/Item.cs:24)
where line 24 is:
inventoryManager.AddItem(itemName, quantity, sprite);
anyone know how to fix this?
itemName is probably not known
is inventoryManager referenced?
or that
Well, now you know that there are different types of layout groups like Horizontal and Vertical, which do simplify your alignment process
Yes, quite handy
thanks
aight ill go check it out thanks
np
Whoa, a new discord code block font :D
Looking sharp
NullRefs are the most common error to have and I know they can be very mindnumbing haha
In your case either intentoryManager, itemName, quantity or sprite can be null
As we haven't seen the AddItem method yet
Please, check them all for being null
Also (i)InventoryManager should be PascalCase if it's a class (which I assume)
No, it shouldn't
public void AddItem(string itemName, int quantity, Sprite itemSprite) {
Debug.Log("itemName = " + itemName + "quantity = " + quantity + "itemSprite = " + itemSprite);
}
š
this is the additem
D:
Classes should always be PascalCase?
Yes, but AddItem is not static, so they're not referencing it directly.
They have a reference for the class, which should be written in thisCase
Ah true
MyClass myClass;
But you're right if it was MyClass.AddItem, where AddItem is a static method
Yeah my bad, was working with static events too much xD
I distrust Singletons after my last game jam
Alright, everything is great with your AddItem's parameters
The intentoryManager is thus null
How do you assign it?
Maybe in awake which is not good?
What made you distrust them?
They are quity useful if done correctly
Input is not working for some reason
Yeah I am using them
Which is ok
But I rather use events or Actions than Class.Instance.Method now
You have to subscribe to the action
Let me write down how
Please, consider writing the full problem in a single message
Where is GetMoveInput referenced?
Update
I have mentioned it, that's why I asked to write the full issue in a single message
I see it, there are 2 more references
wait I don't really understand the question, you mean where do I use inventoryManager in the code?
Here, I'm using it to move my player
But the input values are never changing
always 0
I'm writing down how you use the new system
No, I mean how do you assign it? Is it serialized or do you get it in e.g. Awake or Start?
inventoryManager = GetComponent...?
Just wait a sec
oh uh here
void start() {
inventoryManager = GameObject.Find("InventoryCanvas").GetComponent<InventoryManager>();
}
You don't get an error here, do you? In this case there's no InventoryManager component on the InventoryCanvas
You have to subscribe to input actions like this
private InputActions _inputActions;
private void OnEnable()
{
_inputActions ??= new();
_inputActions.Player.Roll += DoRoll;
_inputActions.Player.Roll.Enable();
}
private void OnDisable()
{
_inputActions.Player.Roll -= DoRoll;
_inputActions.Player.Roll.Enable();
}
private void DoRoll(InputActions.CallbackContext context)
{
Vector2 inputVector = context.ReadValue<Vector2>();
...
}
@willow scroll @hot palm Oh it seems like I forgot to add theese :D
Yep
Thanks, that was my problem, yea
No, they don't have to.
They can*
you mean this?
But isn't this enough?
and yes i don't get an error there
Guess I'm using input actions different than others?
You're right, this is enough. You don't have to subscribe the event if you're calling the method here #š»ācode-beginner message
No, you've sent the most frequently used example
Well that makes it easier if this works aswell
If I would want to switch from Player (the inputs used during the game [walk etc.]) and UI (UI inputs). So I should do smth like this right?
inputActions.UI.Disable();
inputActions.Player.Enable();
if I want to switch to UI input
inputActions.Player.Disable();
inputActions.UI.Enable();
In this case you call the method GetMoveInput twice in Update, which gets the same result and is thus redundant. Consider calling it once and storing the result into a variable.
void Update()
{
Vector2 moveInput = InputManager.Instance.GetMoveVector();
moveVector = new(moveInput.x, moveVector.y, moveInput.y);
}
Yes, that's right. This way UI input will be used instead of the Player one
is PlayerInputActions still a thing?
What else would be?
I am not asking about the InventoryMenu field's assignment. I want you to show me the reference to the InventoryManager you've shown in the image
this I assume... right? š¦
The passage where you assign something to inventoryManager in this script
The class where you call AddItem from
If want my player to tp back to the latest safe place after falling to a pit, what is the best way to do it? Do I send I Raycast down each frame and check if they are on solid ground to save that point at latest save point or...? Is there something sorta of stipulated for this?
Depends on the environment, other methods are easier if it's for example blocky tiles. Then you could raycast downwards, check for layer "safe ground" and store that in a list
No, I want you to send me the class which references your InventoryManager script.
public class YourClass
{
public InventoryManager inventoryManager;
}
If it's terrain it can get more complicated. In my recent game jam game I checked if the player.transform.y > 100.0f and store that position in a list every second
Why a List?
Then after falling down, I tp'd him back to the oldest safed place
I like Lists more than arrays
I add a vector3 position every second
and if it's above 30 I remove at index 0 and add the latest position
sorry for the trouble, I think youre referring to this:
public class Item : MonoBehaviour
{
[SerializeField]
public string itemName;
[SerializeField]
public int quantity;
[SerializeField]
public Sprite sprite;
private InventoryManager inventoryManager;
void start() {
inventoryManager = GameObject.Find("InventoryCanvas").GetComponent<InventoryManager>();
}
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.tag == "Player") {
inventoryManager.AddItem(itemName, quantity, sprite);
Destroy(gameObject);
}
}
}
Yeah thsts the problem
Also SerializeField the inventory manager and assign it in the editor
GameObject.Find is just bad
Bcs if you rename the object you never know this script wont work
Also it should be
void Start()
cuz im literally jsut followin a yt vid for this and its like a years behind
plus i only am a 2 days old c# user :/
It's alright
Just know that GameObject.Find is bad
Also the problem here is the
void start()
as unity doesn't recognize it as the start method and won't call it at the start
Getting Large and lower case right is important
that was totally the problem... i feel really dumb now
After 2 years I still make silly mistakes, it's normal
It's always good to go get some fresh air and come back
Do Unity developers even get some fresh air?
Idk about you but my brain doesn't function without fresh air
Alright, you definitely seem more normal than me
Normal
But why a List instead of only one value?
I had a weird terrain, so I wanted to tp back 30 iterations
What if the last position isn't safe anymore?
Then just don't save it
Problem is I had slopes you could slide down, not go up but can jump down
the slope end was above 100
You didn't seem to understand. What if the position was safe at the moment of saving it, but not it's not safe anymore? If you may have this sort of case, you'll probably want to have a list instead of a single variable.
So the last safe position was safe but not meant to be on
So jumping down would get you back to a safe and correct position
What if you don't have ANY safe position then?
Then fix your game?
anyone knows any ways to detect which side of the collider an object has collided with? im trying do like a mario stomp on enemies typa thing, but i cant find any good tutorials
For a minecraft prototype I had every block cast 6 rays and dont render the face of the block a raycat would intersect a collider
(had 6 colliders)
I mean, you are the one implying that previously safe positions may become unsafe later. Very few games do even have that.
So in 2d you would want 4 colliders, 1 for each side
I think it's maybe tedious to set up but you can do more stuff afterwards
Also prefabs>>
We are here to cover all cases š£
I mean you can try with only one, if it works for your game, great
Tidali mentioned using a list, so I suggested the possible reason for its usage. You don't have to use it if you're sure the positions are always safe
Although the logic for using a list won't be that much harder than with a single variable
Yes, there is a similar question on Unity's forum
https://forum.unity.com/threads/is-there-a-way-to-detect-which-side-of-a-collider-is-hit.528687/
I have a list of a class, and it also contains classes that inherit from that class, how do I check if its a class that inherits from it
eg.
List<Element> elements = new List<Element>();
and it contains ObjectElement which inherits from Element
loop over the list and check element is ObjectElement
The collection itself has nothing to do with it
ok
if i change a value (like SubEntityData) inside originalProfile, will it also change the one inside blackboard.AttackProfile
like, is originalProfile an exact copy, or does changing it also change the place i got it from
Do you've got any errors?
nope
Nothing wrong with the code. Your problem is likely something else (script not compiling/updating for some reason)
right mouse the script -> reimport
That doesn't look like the inspector for this script btw
Can you show the entire class?
Is it the Item class?
wait
The code isn't what's shown in the inspector
i imported the wrong code file... so sorry guys :L
How come the functions are not showing in inspector events? Am i missing something
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float speed;
public UnityEvent onVictory;
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void Move(Vector3 movement)
{
rb.velocity = movement * speed;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Victory"))// enemy
{
onVictory.Invoke();
}
}
...
public class UIManager : MonoBehaviour
{
public TMP_Text victory;
public TMP_Text gameOver;
// Start is called before the first frame update
void Start()
{
victory.gameObject.SetActive(false);
gameOver.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
public void ShowVictory()
{
victory.gameObject.SetActive(true);
}
public void ShowGameOver()
{
gameOver.gameObject.SetActive(true);
}
Did you reference an instance?
If you're referencing the class script the instance methods will not be visible
Oh. so you always need to reference to the gameObject that contains the script, rather than link it straight to the script. always.
why doestn my particle system show up? even tho im instiatiing it
i have a suspicion that its cause of this
Where do you start playing it?
in here im instantiating it , for the guy im following the tutorial works fine but for me doesnt seem to work
It's not set to play on instantiation, you need to actually start playing it
how can i play it when its a gameobject and not a particle system?
reference your prefab as as ParticleSystem
You can instantiate it as its type and get reference directly
Instantiate returns whatever type you gave it.
Intantiate<ParticleSystem>
If the type is a component type (like ParticleSystem), it copies the entire object the component is attached to
yea, implicit is fine too
this would require the prefab to be referenced as as ParticleSystem
the object parameter is T in the generic version of the function
Instantiate<ParticleSystem>(gameObject);
this is a compile error.
i see yea, there's a screen with prefab reference
they're all GameObject-typed
wait how can i reference my prefab as an particle system ?
by changing the type of the variable from GameObject to ParticleSystem
You will then need to re-assign the prefab reference.
The serialized data will still point to the prefab's game object.
When you drag the prefab back in, you'll serialize a reference to the prefab's ParticleSystem
Alternatively you can set particle system to play on instantiation in properties. But this way would be more of a learning opportunity
guys i just watched a video on how to detect collision and that thing is working good but how do i detect if the object is not colliding the ! is not working.
im working on a shop system like red dead 2
true that
Show your code.
like in the inspector where i set the particle system?
that's why i need that
ok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.IO;
using System;
public class ShowMenuBook : MonoBehaviour
{
public GameObject Canvas;
private void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
Canvas.SetActive(true);
}
if (collision.gameObject==false)
{
Canvas.SetActive(false); // this is not working
}
}
}
the ! is also not working
and now i just this 
You need to assign it in the inspector, yes.
The pattern for collision detection doesn't have anything to do with the if statement.
i already did
Note that you don't need the explicit generic type parameter.
Foo myvar;
Instantiate(myvar);
Instantiate<Foo>(myvar);
Lines 2 and 3 are equivalent.
What do you think
collision.gameObject == false
means?
You would use OnCollisionExit
idk i learned collision detection like 5 minutes ago š¤£
if you don't know what it means then why did you write it?
Yeah doesn't make sense
valid (:
to see if it works
but you should think about what it does mean
Collision.gameObject is the game object that you interacted with in the collision.
OnCollision is called, when something is colliding. So checking for no collision is interesting
xD
A collision cannot occur without a game object because a collision must involve a collider, and a collider must be attached to a game object.
yeah but how do i type collision.gameObject.tag == "Player" == false ? š¤£
oooh mbmb
again i just learned
When checking if something is leaving the collision, use OnCollisionExit
like 5 minutes ago
if you want to detect when a collision ends, you should use a completely different method
ohh
OnCollisionExit sounds appropriate
it's not wrong! i'm just pointing that out (:
i don't think i've ever used Instantiate with an explicit type parameter
oh good to know then š
this might work
That sounds reasonable.
Also don't do
collision.tag ==
Do this instead.
collision.CompareTag("Player")
Ive been trying to add this method to my player controller script but when i call it my player stays in the same position for some reason. any idea why ?
public void TeleportPlayer(Vector3 newPosition, Vector3 newEulerAngles)
{
_controller.enabled = false;
transform.position = newPosition;
transform.eulerAngles = newEulerAngles;
_controller.enabled = true;
_verticalVelocity = 0f;
Debug.Log($"player teleported to position {newPosition} and rotation {newEulerAngles}");
}
yeh lesgo im going to create the next rdr2 š thank you so much for the help
its working
welp this error appears
idk why im feeling this inner energy
Did you actually change the type of your variable?
currentweapon.muzzleFlashParticles must be a ParticleSystem
Looks like random non valid code again. Remove the == false and use an if-else setupcs if(...) { //we hit the object with said tag } else { //we hit something else }
somehow it didnt save
pain
losing it
Checking tags should look like this
if (collision.CompareTag("Player")) { ...; }
// Or
if (!collision.CompareTag("Player")) { ...; }
CompareTag warns you if you use an invalid tag
! doesn't work
I believe it's also more efficient, but that is less important
Show us line 40
If ! doesn't work, something else is wrong
nothing
Did you re-assign the reference in the inspector after changing the variable's type?
It should return true, when using a valid tag, but not player
Perhaps that's what caused this.
you need to actually do some debugging here. use Debug.Log to check the tag you're getting
i solved the problem so ?
yes and for the smg as well
its working with fen method
Can't believe you do me like this
bruh sorry mate š¦
you're doing nothing with the result of Instantiate
so you're attempting to play the particle system on the prefab
note that this wouldn't cause the error you saw
it's just also incorrect
oh damn
also, you should check what currentweapon.muzzleFlashParticles actually is
i wonder if your current weapon is different from this
now you're overwriting the prefab's particle system with the copy
oh wait, nvm
i cannot read
How do i destroy the parent and the children and not just the trampledHitbox?
dalphat your method is a little rusty š
this doesn't show what currentweapon is though
Can you share the entire script, and also log currentweapon immediately before you try to instantiate its muzzle flash?
The pattern would usually becs var particle = Instantiate(...); particle.Play();It looks like you're trying to play the particle of a prefab or the particle cloned
its a Weapon which is basically a scriptable object that has the gun statas n such
I know. Iām wondering if the object stored in that variable still needs to have its particle system reference fixed.
I should say I need to see what currentweapon holds!
What was the goal? The if-else would only evaluate if the object hit (only occurs on hit btw) was the intended object. If anything else were hit (anything with a collider) it'd do the else.
And youāre still getting the error?
nope
Get the objects parent like this https://docs.unity3d.com/ScriptReference/Transform-parent.html
btw will offline inventory system be compatible with an online inventory system or do I have to create it from scratch ?
oh! okay, you're good then :p
That's a really vague question and I guess it depends on it's implementation
like security and other stuff you know
btw what is an inventory fundamentally in unity some list ?
multiplayer is an entire 55-gallon drum of worms
hahahah
It's a class containing parameters such as a list
i hope its not too hard š
Depending on what you want it to do
If you want to build something that's close to a multiplayer-ready system, just make sure that you separate the display of your inventory from the actual inventory data
YIPPIE IT WORKS
huh š i don't get it ? you mean visuals like UI, GRAPHIC and logic like data list etc ?
in a multiplayer game, you'd probably keep the player's inventory data on the server
the client would send instructions to the server to manipulate the inventory
this means the server can validate whatever the client is trying to do
You could add an offline version which updates the server's version when going online again
Inventory systems are already a major pain point, so I'd suggest just getting some experience with making any kind of working inventory first š
It's fun to prototype systems and it's easier to implement once they are fully fledged
Yeah I know the very basic stuff
GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEnginesForSendingToArray.Add(clonnedEngine);
can I create a list like this to store the clonned objects ?
I want the best toturial by you guys because you guys have the experience and I don't
No I made my last one from scratch so I haven't really watched one lately. Just know that you can use scriptable objects as items
99% of the unity toturials are faster than andrew Tate's Bugatti
you can store the objects however you want, but you don't need <GameObject>. also, i wouldn't have Array in the variable name as it's a list. that's a bit misleading . . .
Well you will have to pause occasionally
And they explain nothing
As noone is answering this rn, I suggest you search it up and click through videos. Surely there are some good ones
Also I dont think it has to be unity specifically
there are no best. we've watched multiple tutorials and use the parts that we like from each . . .
I named them in that way because they have created for just to convert their type to array
there are a ton of them, and they do explain. you have to take the time to understand each line of code and what the intent for that type of inventory is. there are so many different versions of an inventory. you will never find one that fits all . . .
Yeah it depends a lot on the type of inventory you want to make
then, as long as you know what they're for, it should be fine. if you have a list, why do you need to convert it to an array?
because you can't add item to array right?
I hope so
I personally think lists are the better array, could be my limited knowledge tho
Being able to do List.Add and List.RemoveAt is just so good
no, you cannot. arrays have a set size; but if you have a list, why do you to convert to an array? that's what i'm asking . . .
I just love using arrays lol I have to stop this but
Only thing I can think of they're probably faster, as they are constant in size
SerializeField] GameObject[] enginePrefabs;
GameObject[] currentEngines;
ParticleSystem[] currentEnginesPSystems;
List<GameObject> currentEnginesForSendingToArray;
List<ParticleSystem> currentEnginesPSystemsForSendingToArray;
private void SetupEngines()
{
for(int i = 0; i < currentEnginesCodeline.Length; i++)
{
print(i);
string currentCodeLine = currentEnginesCodeline[i];
string[] mainSplit = currentCodeLine.Split('/');
//mainSplit[0] location
//mainSplit[1] engine type
string[] locationSplit = mainSplit[0].Split(',');
float x = float.Parse(locationSplit[0]);
float y = float.Parse(locationSplit[1]);
float z = float.Parse(locationSplit[2]);
Vector3 enginePosition = new Vector3(x, y, z);
int engineTypeNum = int.Parse(mainSplit[1]);
GameObject selectedEnginePrefab = enginePrefabs[engineTypeNum];
GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEnginesForSendingToArray.Add(clonnedEngine);
currentEnginesPSystemsForSendingToArray.Add(clonnedEngine.GetComponent<ParticleSystem>());
}
currentEngines = currentEnginesForSendingToArray.ToArray();
currentEnginesPSystems = currentEnginesPSystemsForSendingToArray.ToArray();
}
why would this not work?
clonnedEngine returning null
btw ur missing a [ at the beginning there
yes yes I made it in discord
arrays are more performant because they have a set size and contiguous memory . . .
Love me some uncommented code
currentEnginesCodeline = new string[] {"1,1,1/0", "5,-2,1/0"};
this is my codeline strings
but it still returns null
I have little problem with tilemaps and mouse positions
My localScale on tilemaps is 0.33
why
It's terraria like game, I had to change localScale to set player to be bigger than tiles
Or tiles to be smaller, like 3 tiles = player size
It's always easier to rescale the player according to your world tho
you assign them to an array at the end, but why? that is my question. you already have a list of all the items . . .
Because with this logic you will have to rescale everything you have in the world (except the player)
for(int i = 0; i < currentEnginesPSystems.Length; i++)
{
currentEnginesPSystems[i].Play();
}
I am using that arrays here when you press W. If you asking: You already have list, why you creating the almost same type array again? Can I use lists in this function too? I really don't know about lists.
Okay, maybe it will be easier, I tried to rescale tilemap instead of player, and trying to make it fit in camera, but I forgot i can change camera distance š
Thanks @Tidali
of course you can use a List. Just replace .Length with .Count
ohh let me try
but anyways why it is returning null object?
game clonning that object but can't add to a list?
Yes
Only difference it's List.Count and Array.Length
Glad to be of help 
GameObject clonnedEngine = Instantiate(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEngines.Add(clonnedEngine);
game object clonnedEngine clonned successfully but in the second line, it giving nullreferenceexception
tbh your whole logic is flawed, you dont need to use a list at all in this scenario
Maybe your list is faulty somehow?
Also this
I'm not aware of the previous discussions but your list engine variable hasn't been initialize/assigned a reference to a list - = new List<...>();
Why? Player selecting a spaceship and system creates a codeline for engines. In the game, system takes the codeline and creating engines for spesific locations and types.
List<GameObject> currentEngines;
List<ParticleSystem> currentEnginesPSystems;
these aren't enough?
out of start()
btw dont need to use list since the length is known, unless you will add another gameobject later
Those would be the declarations
currentEngine = new GameObject[currentEnginesCodeline.Length];
for(int i = 0; i < currentEnginesCodeline.Length; i++)
{
...
GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEngine[i] = clonnedEngine;
}
no length is unknown, ships has 3 4 5 engines
You'll need to initialize them before usage using the assignment operator =.
read the above code stevesmith have written it for you
Or have them be populated from the inspector. A good practice would be to have them simply be initialized on declaration if you aren't intending to share referencescs public List<...> myList = new List<...>();
A list is a class (reference type), default value for those is null, unless it's Serializable and Serialized via Unity. Otherwise you need to initialize it yourself
Maybe consider what Steve is suggesting.
Nice! This fixed my problem. Thank you for all you guys helping me, I am going to study lists and arrays more today! @languid spire @hot palm @cosmic dagger @gaunt ice @modest dust @ivory bobcat
[SerializeField] GameObject[] enginePrefabs;
GameObject[] currentEngines;
ParticleSystem[] currentEnginesPSystems;
private void SetupEngines()
{
currentEngines = new GameObject[currentEnginesCodelines.Length];
currentEnginesPSystems = new ParticleSystem[currentEnginesCodelines.Length];
for(int i = 0; i < currentEnginesCodelines.Length; i++)
{
print(i);
string currentCodeLine = currentEnginesCodelines[i];
string[] mainSplit = currentCodeLine.Split('/');
//mainSplit[0] location
//mainSplit[1] engine type
string[] locationSplit = mainSplit[0].Split(',');
float x = float.Parse(locationSplit[0]);
float y = float.Parse(locationSplit[1]);
float z = float.Parse(locationSplit[2]);
Vector3 enginePosition = new Vector3(x, y, z);
int engineTypeNum = int.Parse(mainSplit[1]);
GameObject selectedEnginePrefab = enginePrefabs[engineTypeNum];
print(enginePosition + " " + engineTypeNum);
GameObject clonnedEngine = Instantiate(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEngines[i] = clonnedEngine;
currentEnginesPSystems[i] = clonnedEngine.GetComponent<ParticleSystem>();
}
}
this is my current code if you want to check out
I noticed you're not using quaternions at all...
How disgusting
Sorry I am a beginner.
Good job, looks much better
I'm just joking lmao

No worries, you probably won't ever be using them at all, unless you're a crazy person
Is this a dig at me?
Of course, nobody loves Quaternions, we put up with them as a necessary evil
i am not sure how its getting disabled
Maybe the instantiated object that you're cloning is disabled
Maybe the prefab object is disabled
Is the audio source disabled?
Is Unity disabled?
i mean , i got the audio source on the guns prefabs so i can play diff shooting sounds for diff guns
and i put the respective audio source of the gun prefabs here
The currentweapon is disabled. Please, print currentweapon.gameObject.activeInHierarchy