#💻┃code-beginner
1 messages · Page 711 of 1
Oh can you forward the rule to me?
Second last point in prohibited behaviour in code of conduct
This it?
Didn't even think that rule would be in there lol. Sorry, I won't do it again.
I know but it's all good now. Thank you.
Why am I getting this error even though I assigned the panel in the inspector? Should I send the corresponding script as well?
you might have a copy with the field unassigned
like another object with the same script?
its only on one of my objects
huh. try start with that object disabled ?
yeah its disabled on start
i have this method on a button in the scene
{
panel.SetActive(true);
panel.transform.SetAsLastSibling();
}```
double clicking the error sends me to this line
panel.setactive(true) line
i just put a debug log and the method is registering
the panels are messed up and idk why
panel is assigned in the inspector?
yup
Make sure you don't have two copies of the script on this one object
i fixed it. the problem was cuz the panel wasnt assigned in the prefab. the panel isnt being set active still
the panels in my hierarchy are messed up i think because this is a simple show method that just sets the panel active but the assigned panel isnt being set active s
could it be because its a prefab?
Sounds like you're getting confused with how references work when you're dealing with prefabs
Which script is this and which panel object is it referencing? And where does the prefab come into play?
this is the script: https://paste.ofcode.org/zA8YKuaHQ5iSDhQFjdXVDB
panel is supposed to reference the preview panel that shows the upgrade details when you press the buy button
the prefab was accidental but i just redid the panel without turning it into a prefab and the panel still isnt being activated
hold on
yeah the button isnt activating the panel
the debug i added is showing up in the console but the panel isnt getting activated
nevermind
i fixed it
Can i get some tips from people?
I'm trying to create a game while handling the backend myself. Admittedly, I'm not much of a game developer however i do have some experience in backend. Do people usually use cookies/jwt?
backend stuff is pretty vague, do you have specific issue ?
what type of game uses cookies? especially in relation to unity
just don't attempt to write your own..seen some sketchy stuff lol
"backend" is really vague
Nothing of the usual. Off the top of my head, i just want to allow user to authenticate and save their details such as map position etc, items held.
You are making a game with some networked features? What are those features?
So just... cloud save?
It is mainly offline but i do want to save user progress
yes
one option is to just use Steam cloud save
you barely have to do anything
it's much nicer than forcing your users to create a new account somewhere
Another option is UNity's first party cloud save:
https://unity.com/products/cloud-save
I think one of the issue that this is kind of a research project where they prefer to store the data onsite or within the big providers (I think they should be fine with something like Azure PlayFab too)
yes there are plenty of services offered by the hyperscalers too
Okay first party should be okay too. Would also prefer not to roll my own. Thanks for this i'll have a look.
Thank you!
Unity cloud save is pretty good used it plenty of times and their free tier is decent
How do I access a public list? For public variables, it's just
public MoneyManager moneyTotal;
int oldValue = moneyTotal.money;
But when I do similar to lists, it just makes a new list in a different object.
The part I'm referring to, I // out
You access it the same way as any other field. Maybe provide the code where you try to access the list.
question... not sure why but the Mouse Cursor logic doesn't seem to work here
void MenuActivationMethod()
{
if (isPaused)
{
settingsCanvas.alpha = 1;
settingsCanvas.interactable = true;
settingsCanvas.blocksRaycasts = true;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
else if (!isPaused)
{
settingsCanvas.alpha = 0;
settingsCanvas.interactable = false;
settingsCanvas.blocksRaycasts = false;
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
Doesn't work in what way?
the cursor stays visible and it doesnt get locked in place
the settingsCanvas logic works as intended though
did you like click in the game view ?
yes. doesn't seem to like it
I have a TEMPORARY workaround with using Playmaker to grab the isPaused variable and then use FSM logic to do it.... but I am trying to do it in C#
But I can confirm the mouse logic at least works.... with Playmaker. Just not with this code. (Obviously I dont have both at the same time)
It’s in the screenshot. Owneditems getting checked if things are in the list
That's not "accessing from another script" though.
Oh you mean the source script. I’ll get that when I’m home
And what does "doesn't seem to like it" mean? Errors? Crashes?
This is the sourece script for that list. Declaring it as a class field in this script obviously creates a new list. That's not how you access fields of another script, regardless of whether it's a list or not.
Okay, then how do I access it because that’s what it told me to do when I looked it up
otherScript.field assuming the field is public.
just doesn't work at all
no errors, warnings, or anything
Thank you
turn off the Playmaker FSM but turn on the C# Script? = nothing works
turn off the C# script but turn on the Playmaker FSM? = it works
which from a very basic test perspective..... is fine I guess.... but when I do a REAL menu and settings and all that good stuff.... it cant be like this
and a lot of online searches seem to say its supposed to be Cursor.lockState or Cursor.visible as shown in the code above
Stop crossposting.
#📖┃code-of-conduct
if you have a specific issue, !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
if you just want work done, !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Just a heads up, otherScript.field also needs a declaration which is what I was tryna do
Was the question resolved?
I'm working on making a platformer player controller template for a tutorial I'm working on but I'm trying to remember which parts of a player controller is best to put in the fixed update. I tried leaving the inputs in update and the rb.velocity in fixed update but it kept making jumping very odd. Should I just leave everything in update or am I missing something?
Nope. I thought I was able to declare it, but it's still acting like there are two different lists
what was your question?
your description of the issue is kinda vague. perhaps show the issue and relevant !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
https://paste.myst.rs/1k6hhuz6 This is the code I have. I use rb.velocity and not addForce that might be an issue
a powerful website for storing and sharing text and code snippets. completely free and open source.
with using fixedupdate
https://paste.mod.gg/uvyiikeiojmz/1 Here's mine. I can't rename the scripts, but in DateDisplay, I'm trying to check for a certain thing in the list made in TimeDisplay
A tool for sharing your source code with the world!
where are you reading the value of the list?
it would be like get reference of TimeDisplay and that that reference ex. TimeDisplay.ownedItems
if (listToShowBoughtItems.ownedItems.Contains(objectName))
listToShowBoughtItems is the actual script name
I just can't rename the tabs on this website
and you're sure this name change is on both the script and unity
If you changed the name just in unity it would duplicate the script but inside both scripts it would keep this name
That could be your issue
Unless you didn't change the name
Yes
and what's the error?
In my game, I purchase a thing, and in the Buy gameobject, it shows the list and it shows that the thing is on the list. When I look at the list on a different gameobject that uses the script, there is nothing on the list
In the script ShowboughtObject have you passed the list where the bought objects go to the listtoshowboughtitems variable? Cause in the script you create a new list but never get a reference to this list
I have listToShowBoughtItems.ownedItems.Contains(objectName), but if that's not what you mean, then I don't know that I have a reference
in the inspector
you have to drag and drop the script for the listtoshowboughtitmes into that variable
you're trying to get an object from nothing
You are creating a new ListToShowBoughtItems object instead of using the existing one. It should be [SerializeField] ListToShowBoughtItems listToShowBoughtItems; and then drag the object there
(the instance of the script*)
yea
Like this?
make it a [SerializeField] or public first
and then put the script into the new filed that will show up
The list? It is public
this
Ah okay
yup, two things to note specifically
anything deriving from MonoBehaviour cannot be made by doing a new() instance of it, they don't work.
even if that worked, this code points to that new instance of it made via code, and not the instance of it that currently lives on the same object that your now referencing correctly
Gotcha gotcha
this worked since you created a new script, it foudn a list but it was empty so it wasn't then activating that if
Yeah
Quick question - For respawning in a platformer game Adding checkpoint mechanic should I reload the scene and set their position to the latest checkpoint or just set their position without reloading scene?
It depends on what is in your game at the moment. If you have some objects with a state that should be reset whenever your player respawns(like a boulder that chases a player), you need to either reset the boulder to its position or reload the scene.
Yeah I was thinking about that. I could maybe make a bool and you can choose for each level
hello, I'm trying to make a gun system for my game, so I watched a tutorial showing a system that works for all type of gun, but it doesn't work, do you think there's an issue in the script or the problem is with the particles?
Maybe you should describe what is supposed to happen and what happens instead
there should be a muzzleflash effect at the firepoint and an impact effect at the HitPoint of the raycast if there is one, and none of that happens, I've tried multiple particles effects, none of them worked so now I assigned particles for explosions, not really for a normal gun
Have you tried logging any messages?
no, not yet
Well.. place some logs and see what's occurring and not occurring
Okay ill do that
Anyone have any idea where UnityEditor.SpriteEditorWindow lives in the Unity codebase now?
Quick question on performance, I'm currently deciding between List or Hashset and this is my use case:
-
n <= 5
-
The idea is that I want to use this data structure to determine whether to pause some coroutines.
-
I don't care about order and while duplicates are not a detriment, it's probably ideal that they are not a thing.
-
The data type of the elements in my structure will be strings.
-
Because I'm using it to pause coroutines, then potentially I would be checking this every frame at runtime.
Pretty much, I feel like because of the frame by frame checking it's probably best to go with Hashsets, due to faster lookup, but because of the number of elements being so small, I'm not sure if I'm just better off going with a list?
Sorry if this is the wrong place to ask this, thought it made the most sense to ask in this channel.
The reason I have done this frame by frame, is because I'm using coroutines to update progress bars
n <= 5
it will not matter in terms of perf.
you can start worrying about perf when n gets to like, the 10000's range
write what makes sense first, don't worry about perf now - that's called premature optimization
Kk got it, because I get both of the data structures, although lists are easier syntax to understand.
Should I use a Stack to keep track of menus UI?
if that makes sense for the behavior you want, sure
I'm more concerned about the performance
are you gonna have 10000 menus at the same time
no? then there's no perf concern. computers are fast
don't worry about perf until either it becomes a problem, or you're dealing with stuff in the millions
{
if (Physics.Raycast(interactionPoint.position, interactionPoint.forward, out RaycastHit hit, interactionDistance, interactableLayerMask))
{
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
Debug.Log($"Looking at: {hit.collider.gameObject.name}");
if (Input.GetKeyDown(KeyCode.E))
{
interactable.Interact();
Debug.Log($"Interacted with: {hit.collider.gameObject.name}");
}
}
}
}
what is causing this not to trigger , each interatbale object on with the interactbale layer has a script that implements the IInteractable interface and cuase the interact fucntion implmted on each script , it detects which objects i am looking at but nothing happens when are press e each object has collider and is not set to trigger.
UnityEngine.Debug:Log (object)
Interactor:Update () (at Assets/Scripts/Interactor.cs:17)
Looking at: cardboardBoxClosed
UnityEngine.Debug:Log (object)
Interactor:Update () (at Assets/Scripts/Interactor.cs:17)
The first thing to do would be to either set collapse on in the console or remove the "looking at" debug because it's probably drowning out the "interacted with" debug. And make sure there are no errors shown when pressing e
Does anyone have been struggling to do a Ladder system with tilemap collider in unity ?
its working somehow
can someone help e i have a grind system and a paht with fences the fences should go away if a path is in fron tor to the side my codes js dont work
{
public void Interact();
}```
```public interface IInventoryInteractable : IInteractable
{
void Interact(InventorySystem inventory);
}```
will this work as a good enough interacting ssytem or is it bad and not scable if i need differnt types of interactbale objects in the future
3x ` then cs at the start of a code block
i will always be inherting from the IInteractable
hey i have an issue when making a camera controller, im really new and this is the first real attempt at unity so please do inform me of any mistakes, i was following a tutorial and i found an issue where i cant move the camera left and right could someone help me out?
public class FirstPersonCameraController : MonoBehaviour
{
public Transform Player;
public float mouseSensitivity = 2f;
float cameraVerticalRotation = 0f;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float inputX = Input.GetAxis("Mouse X")*mouseSensitivity;
float inputY = Input.GetAxis("Mouse Y")*mouseSensitivity;
cameraVerticalRotation -= inputY;
cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
transform.localEulerAngles = Vector3.right * cameraVerticalRotation;
Player.Rotate(Vector3.up * inputX);
}
}```
(im on win11 and my unity vers is 6000.0.51f1)
You've probably set up your hierarchy/ references incorrectly in the editor
could you help explain or just link me to some where i can learn hierarchy to possibly fix this?
You would need to share some screenshots showing how you set it up
what would you need to see?
Your hierarchy and the inspectors of the objects involved
is this good?
Yeah so it's clear what you've done wrong here
and i apologise i just realised what you ment by heirarchy
You put the script on both objects
This script should only be in the Main Camera object
It should not be on the Player object
i change to using thsi isntead for now using UnityEngine;
{
void Interact(InteractableContext context);
}```
```public class InteractableContext
{
public InventorySystem Inventory { get; private set; }
public GameObject Interactor { get; set; }
public InteractableContext(InventorySystem inventory, GameObject interactor)
{
Inventory = inventory;
Interactor = interactor;
}
}```
Hi. I started coding movement in a 2D project and I'm only using basic shapes right now (rectangle for player, ground, walls etc). I made a Slide that works, the problem is that if I'm too close to the obstacles that I want to slide under, my boxcollider size and offset aren't reduced fast enough it seems, so I stay stuck on it and don't go under. I put the boxcollider.size and offset code in the Input to change the size immediately, I even tried putting Physics2D.SyncTransforms(); under the boxcollider code, but it's not working. Any tips?
I don't understand why OpenMenu() breaks my pause logic, even though isPaused is set to true
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if(_isPaused == false)
{
_isPaused = true;
OpenMenu(_pauseMenu);
PauseGame(_isPaused);
}
}
}
public void OpenMenu(GameObject menu)
{
if(_menuList.Count != 0)
{
_menuList.Peek().SetActive(false);
}
menu.SetActive(true);
_menuList.Push(menu);
}```
It does not load the assigned UI menu, nor does it pauses the game, unless I remove OpenMenu()
That code will only do anything if _isPaused is false so if it's true then not doing anything is expected
Initially it's still false, I checked it. When I press Esc, it becomes true, but nothing happens
You need to do some debugging and make sure no errors show up when you press esc
with a function that easy to understand it should be clear whats wrong
Oh, I have to instantiate the _menuList stack first. It did not recognize the reference of the stack
oh so there was a null ref exception?
Yeah, I did not see it earlier
Is this occurring in the Editor? Trying a different hot key may also help. Escape in the Unity Editor may have other unintended behaviors.
It should be the first thing to check
in editor it wont eat up inputs but esc will force a mouse unlock
so in my game the player will be able to sit down so should i have the camera seperate and just disable player movement or is there a cleaner method?
I did this for a car scene, just make it a seperate controller script for that in chair camera
i don't know how i feel about that method also i have an issue so that when you look at the chair and try and get off it gets right back on...
no clue what you want me to do with that information lol
sry nevermind.
should i do a state machine for swapping from outside the car to inside? (first person btw)
thats up to you really. Whatever is easier, you can , or just switch the objects / controllers
just FYI, this isn't a social space. if you need help with something then !ask otherwise please don't spam nonsense in the channels
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
I have a scene change where the player as to walk to a portal to have the final boss fight,
the enemies need the player Transform to detect where it is but because the player only goes to the boss fight scene when he walks through the portal how can i put the players transform in the Enemies script inspector? dont know if this sounds dumb or not
You can't put it in the inspector. You will need to get the reference in a different way
What do the enemies use the player's Transform for?
okay this may sound very dumb ( and it is )
this is for my programing class and the prof just gives us scripts and doesnt tell us anything abt it which is honestly pretty stupid and i have complained
the players transform its in a state machine that he did and just gaves us without any explanation
i think its for player detection but honestly not quite sure as he just gave us the script and told us to use this
well without details it's hard to say. There are a few options in general though:
- Opportunistic assignment. Basically using something like a physics callback (OnTriggerEnter) when the player gets near the enemies to get the reference.
- Use the singleton pattern with a static accessor property, assuming there is only one player object at any given time
- Something like FindWithTag
- Use a static event for the player to announce his entrance to the scene and pass the references
To get coding help, usually you'd provide some necessary information about the problem/behavior, share code and screenshots etc
I have the player in a singleton pattern to keep the health and some other variables, but its just the simplest you can get singleton nothing fancy
then use that
you already have it
(no idea how that's related to "keeping health" etc though, that doesn't make sense to me)
no clue either the prof just told us to use that
honestly this class its giving me more quesitons about programing than answering
learnt more with the internet than the prof
his explanation was that because it doesnt destroy it doesnt reset the health and variables numbers that you had
i think normally i skip this classes as i dont learn anything xd
yeah will use it
this professor get their teaching license in a cereal box ?
sounds more like this person isn't paying attention in class and skipping classes so they aren't fully understanding the information provided by the teacher
could be yea
programming has a lot of concepts, its very rare they will throw you to the wolves like that
honestly wish it was that way, when im in class i pay attention, the professor does not explain the things
he says we are supposed to know this things because we already had 1 semester with another prof no clue
sounds like you didnt pay attention last semester then lol
its still pretty awful if you actually asked for clarification and they "refused"
i passed with the best grade possible
xd payed attention
If the player is from a different scene, you'll not be able to reference from the inspector. Since you've got the player as a DDOL, with the Singleton pattern you ought to be able to access-reference the Instance property.
{
player = PlayerManager.Instance;```
thank you sm for the help! will check that out
hey guys, how do i stop my sprite from completely stopping movement in any direction when it collides. it wont slide on the floor thing i made like i wnat it to, it just stops moving no matter what i do
eh there isn't enough info on the actual setup
alright umm
"what I want it to do" vs "what I coded it to do " are different thing
alright, i coded my triangle to move when i press wasd (using addforce). i have another square below it with rigidbody2d and boxcollider2d and the triangle falls and hits the square and stops moving. i try to move it with wasd but that doesn't do anything. it works while the triangle is falling though.
my script is here: ```cs
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
InputAction moveAction;
public float speed = 5;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
moveAction = InputSystem.actions.FindAction("Move");
}
void Update()
{
Vector2 moveValue = moveAction.ReadValue<Vector2>();
rb.AddForce(moveValue);
}
}
Look in the inspector and verify the force being applied to the Rigid body?
wdym
Check the rigid body component in the inspector
There ought to be some visible fields below (may be collapsed) that show velocity and other useful data.
A random example from the net
Hows the documentation?
they are basically stuck at 0
its good
This is while the application is running and when trying to move, correct?
Try logging moveValue and rb.linearVelocity after your addforce line
is the movevalue too low?
I was trying to avoid spamming the console but that would be the best method
not me 😄
Yes
Maybe it's not related to the script but rather your Input Action?
Log move value as Digi suggested
If it's always zero, you've simply got no input from the action - misconfiguration etc
No it works when I’m in the air or when i lock y value but it immediately stops everything when i hit the square below
Do you've got some script that disables/stops your input?
Nope ive only writtwn the one script. Im a complete beginner soooo i havent reall done anything and im spending my
Time learning unity
Do you've got any errors in the Unity Editor console window?
No
Can you show a screenshot of your move value and linear velocity?
Console logs like Digi had suggested
are you using addforce to move on ground
If they're able to move in the air but not on the ground and it's inverted by chance... 
Yes
I wonder if they move addforce ground may have too much friction for the amount of force applied
thats what i was thinking but idk how to change friction
they do have physics material you can change it on, before doing that you should confirm thats what it is also have you logged the velocity like suggested, whats the value on ground
The normal process would be creating a new physics 2d material, modifying its parameters (friction etc) and applying the physics material to the object
https://docs.unity3d.com/6000.1/Documentation/Manual/2d-physics/physics-material-2d-reference.html
To create a Physics Material 2D, go to Assets > Create > 2D > Physics Material 2D.
Hi everyone what is the correct way to get value from multiple input after click on a button or press enter?
what kinda input we talking about ?
almost everything in computers is input -> output
I'm talking about form
doesn't help lol
what form ? like TMP_Input ? legacy Input ? www. ?
TMP_Input
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class GetInputOnClick : MonoBehaviour
{
public Button SendBtn;
public TMP_InputField TextInput;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
SendBtn.onClick.AddListener(GetInputOnClickHandler);
}
// Update is called once per frame
void Update()
{
}
public void GetInputOnClickHandler()
{
Debug.Log("Log input:" + TextInput.text);
}
}
usually .text or just listen for the OnValueChanged
is correct the code above for single input?
should work fine yea
is correct to attach the script to Canvas Element?
you can if you want ,. personally i dont
so what do you suggest?
PS: Sorry for the noob questions but is the first time programming in csharp and Unity and I'm little disoriented
is there way to make compiling faster
i diaabled domain rolaid, helps but still super slow
10seconds per code change
driving me insane
get better cpu lol
You have two options:
- Better hardware
- Purchase HotReload on the asset store
Unity is addressing the compiling times in Unity 7, but until then it is what it is.
hotreload is low key garbage no? causes lots of errors ? correct me
How do you want me to correct you?
am i wrong
idk maybe cuz unitys already builtin hotreload is 🗑️
When I say purchase HotReload on the asset store, I mean the third party plugin.
yes yes, but how does it work how is it any different
Have you used it
Because it works? The underlying nitty gritty is irrelevant.
It's high key pretty good
it's different in that it actually exists. unity does not have a proper hot reload built in
There's that to. Domain Reloading has nothing to do with compiling times when making code changes. You're getting confused there too.
That's for starting up play mode.
Hence, get Hot Reload
anyway i will look at that hotreload
Do you want solutions or do you want to complain?
Because it sounds like you just want to complain
any bad limitations?
Like, as in worse than waiting however long you are for code compiling?
limitations like doesn't support some libraries, maybe reflection or generics or doesn't reload some things
You can read the documentation and reviews for that, if those limitations exist.
alright then thanks. one more question how did u know un7 will fix it is there blog and any idea when un7 coming
Are there alternatives to using addforce for movement or is that the primary suggestion?
Tons.
Setting velocity directly
Using MovePosition
Using a CharacterController
Using transform
Using Kinematic Character Controller
Using Animations with Root Motion
It depends on how you want it to move
usually never move your character with a rigidbody. unless you know what you are doing
Of all of the wild things I suggested Rigidbody is not the one you should be saying to avoid
Rigidbodies are fine
Depends on how much you'll have to do-undo.
and use collision functions unity provides
No... that's what the physics engine is for
It is if you want your character to have physics
you want something deterministic and fully controllable
Again, it depends on what you are trying to do
yes just what j said
unless you know what you are doing, any of the above (except transform position) is not good
I would say of the things I suggested, Transform Position and Root Motion are the only ones you should avoid
rootmotion yes
transform position + capsule collision functions and a custom gravity are the best
and not hard to code
imagine thinking that moving a character using its transform is a good idea immediately after complaining about needing to "manually calculate physics"
You'll need to code all of your collision logic by hand
If you're going to do that, you really should be using a Kinematic rigidbody
If you specifically want to avoid dynamic physics, the step down from that is "Kinematic Rigidbody using MovePosition" not "Manually via transform"
Rigidbody physics will simulate a rigid body physics system. If you're not needing complex physics interactions (specifically rb physics) you can simply move with transform (teleporting) can physics casts. If you don't want to reinvent the wheel, you can settle with rb or some asset store physics system and try working around whatever isn't preferable.
hey, i proposed/advised against the usually correct solution and its your choice.
Is there a gel body or smthing like that? Js curious
Something that bounces like slime
there is no softbodies by default
Check out the asset store, perhaps
oh ok
Not built-in
It's actually a very very complicated problem in game development
isnt the asset store for assets? What other stuf is in there
Softbody physics are significantly more difficult to compute
Assets
Wait i dont think ik wgat an asset is then
A file in your Unity project
Isnt softbody a component then
no
Oh
Not built in
It's actually a very very complicated problem in game development
Softbody physics are significantly more difficult to compute
But u cant obtain new components or smth?
What do you think a MonoBehaviour is
Idk 🤷
if you add an asset that adds new components , otherwise no? they have to come from somewhere..
An asset might add non built-in components.
for CCD usage in scripts, is unitywebrequest the only way to do it?
i was thinking i could add another
using this;
Can you elaborate on what you mean by "CCD"?
cloud content delivery
Don't you use the Addressables package for that? https://www.youtube.com/watch?v=5IvPPI7YnwU
thanks for that
why isn't my projectile moving?
public class Fireball_Behaviour : MonoBehaviour
{
public float fireballSpeed = 10f;
private void Update()
{
transform.position += transform.right * Time.deltaTime * fireballSpeed;
}
if you have a Rigidbody on it why are you trying to move it via the Transform?
Show the inspector of one of the ones in the scene after you spawn it
(i dont reallly know i just copying the youtube tutorial)
Sounds like a bad tutorial.
The other thing I would check is - are you setting Time.timeScale to 0 somewhere?
but you absolutely don't want to move a Rigidbody via the Transform like that
Send code
You don't appear to have this component on the object, or you haven't saved it. There's no fireballSpeed on this component
There's a script with that name but it doesn't match the field defined in the code snippet
oh you're right
So it's either a different component with that name or it hasn't been saved
yeah probably you haven't saved your code @rotund root
I saw one variable and assumed it was the speed
i saved, i can see the green bar on the side
well somethign is wrong because we don't see the right variable in the inspector
public class Projectile
{
public float speed = 10f;
public Vector3 position;
public Vector3 direction;
public Projectile(Vector3 startPosition, Vector3 moveDirection)
{
position = startPosition;
direction = moveDirection.normalized; // Ensure direction is normalized
}
public void Update(float deltaTime)
{
position += direction * speed * deltaTime;
}
}
Why are you suggesting a POCO
i reapplied the script to the prefab and it shows up now
Is it moving now?
(Assuming the speed is non-zero)
now i'm getting this error 🐒
// Fireball spawn
if (Input.GetKeyDown(KeyCode.Z))
{
if (isOnCoolDown == false)
{
Instantiate(fireballPrefab, LaunchOffset.position, transform.rotation);
isOnCoolDown = true;
StartCoroutine(FireballCooldown());
}
}
}
you didn't assign the prefab variable
The object you are trying to instantiate is null
What type is fireballPrefab
Definitely looks like you have two scripts with the same name
And your variable of the other script, the one with Lifetime
oh i removed that part when was asking the question above
If you're using rigidbody physics you should probably set velocity rather than teleporting with the Transform position property. cs public Rigidbody2D rb; private void Start() { rb.linearVelocity = transform.right * speed; }
that's for despawning the fireball
oh yeah i know what's wrong now, a typo in the playercontrol cs, thanks to whoever mentioned that and deleted within 1 sec
its working now!
can i get help with unity net code here
I'm not getting any intellisense on my C# Scripts. I don't know if my code is correct or not since it can't find the references
I have the Unity Extension, Visual Studio Editor package on Unity, and C#/C# Dev Kit Extensions
so did you setup in unity too ?
if you did all the regular steps check https://unity.huh.how/ide-configuration/visual-studio-code#if-you-are-experiencing-issues
the .net sdk part especially
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
thanks!
Guys I'm making flappy bird with a gun and for my script that spawns the pipes I want to spawn other things to and not have them overlap any idea how?
its possible to do some type of physics overlap to check if area is clear to spawn .eg OverlapCircle
there are other ways but are more math heavy
you can also do poisson disc sampling
k thanks
What is the purpose of ‘static’ within a function? It makes the code run otherwise it’s void?
It makes that function belong to the class itself rather than any specific instance of that class
I’m getting lost on the “specific instance” part. Sorry, I’m completely new to programming. Like I understand it’d belong to boolian if I wrote “static bool” but what would the specific instance be in something like this:
static bool isPositive(int x) {
return x >= 0;
}
I understand it’d belong to boolian if I wrote “static bool”
well that's certainly untrue
Does that not define it as “bool”?
it would be a static method (as in a method not associated with a specific instance of the object) that returns a bool. it has no other association with bool
bool is the type. static means its belonging to class
Eg MyClass.isPositive(num)
The script is not the object. It's a pattern that describes how that sort of object should behave.
You make a script Cat and it is not the same as a Cat. It is, effectively, "How to Cat".
I have three cats. Each one has the script Cat that has a method void Feed(). I feed one cat. It calls Feed() on that cat. The other two have not been fed.
A static method belongs to the concept of Cat itself rather than any individual cat.
Thank you all so much. This definitely helped me understand it a lot more than the tutorial I was watching. I appreciate the help!
i got this code
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
player = GameObject.FindWithTag("Player");
spawnPoint = GameObject.FindWithTag("SpawnPoint");
if (player == null) Debug.LogError("Player not found!");
if (spawnPoint == null) Debug.LogError("SpawnPoint not found!");
if (spawnPoint != null) player.transform.position = spawnPoint.transform.position;
else Debug.Log("No spawn point");
}
this is to make the player spawn in a specific point ( might not be the best option )
but the player doesnt spawn in the right place, when i used the debugger all of this happens and then the scene loads which i think this is why
any clue on how can i delay when this script happens or make it load only when the scene is loaded?
i was suggested by a class mate to use a singleton, dont know if that would work or not
Is this for your enemies? I don't see why you would use this instead of just Start
any idea on how to fix this? I need to drift instead of flip over
Your car needs a lower center of mass
You can change it in code on the Rigidbody
do I change that in the inspector like Rigidbody settings?
this is for the boss battle
my professor wants a scene change to a new scene inside of a castle, when the player spawns he just spawns at a weird location and im trying to make him spawn in the empty that i placed in the map
idk how to open the code foe rigidbody
Right, so I'll repeat the same question - why not use Start?
the empty its in the second scene
if its on start its in the other first scene
or can i make it on start in the second scene
wait
if i make the script another way and attach it to the empty
Yes, that latter thing
wouldnt that make it on start of the second scene?
Start is run on objects, not scenes
so if the object is in the second scene
and its already placed before hand, wouldnt that make the start of the object once the scene loads?
When you load a new scene, all the objects that are activated in it will run Start after the scene loads
okay, ill try to make this in a empty and see if it works
thank you
You could put it on the spawn point object, which can then find the player in Start and move the player to itself, for example.
yeah
thank you would kiss you rn
hi, how would this go on 3d?
{
if (HasHitValeria) return;
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(meleePos.transform.position, MacheteRange, 0f, victim);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out valeriaController64 enemy))
{
enemy.TakeDamage(meleeDamage);
HasHitValeria = true;
}
}
}
i know i have to put the vector2 into vector3, but the other parts are what seems complex
what "FirstOrDefault()" does?
switch overlapbox for physics2d to overlapbox for physics class
its an extra float, adjust the axis as needed . At least with 3D you can use the physics debugger and see what the physics queries look like accurately compared too gizmos
public class CameraMovement : MonoBehaviour
{
public float XRotation;
public float YRotation;
public Transform player;
public float mouseSensitivity = 3f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
PlayerInput();
}
void PlayerInput()
{
XRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
YRotation += Input.GetAxis("Mouse X") * mouseSensitivity;
XRotation = Mathf.Clamp(XRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(XRotation, YRotation, 0);
player.transform.rotation = Quaternion.Euler(0, YRotation, 0);
}
}
``` for some reason my player isnt rotating
first or default.
if it doesnt have an item it returns the default value of the type
so
List<int> thats empty
would return 0
oh, ok
btw do this script may present some issues like idk, optimization or smt?
{
if (HasHitValeria) return;
Vector3 macheteRange = new Vector3(attackRange, attackRange, attackRange);
Collider[] hitEnemies = Physics.OverlapBox(meleePos.position, macheteRange / 2, meleePos.rotation, victim);
foreach (Collider hitEnemy in hitEnemies)
{
if (hitEnemy.TryGetComponent(out valeriaController64 enemy))
{
enemy.TakeDamage(meleeDamage);
HasHitValeria = true;
break; // Avoid hitting multiple times in one swing
}
}
}```
NonAlloc version is much better to use
you just have to predefine size of collider[] with a variable beforehand
nonAlloc?
Which is faster on the internet: free Proton 2 multiplayer or dedicated server?
when you do physics queries with multiple results they usually have a nonAlloc version , meaning Non-Allocating . it might be fine if you call this once in a while but calling it often will create a new array every time , it can get slow
so what i should do on the script?
define the size of max amount of colliders you think you will hit with Collider[]
how
wdym how ? you surely made an array in a varible before
i dont recall it
btw this is the og code
Collider[] colliders = new Collider[MaxSize]
im just doing random stuff for check if works on 3D
Which is faster on the internet: free Proton 2 multiplayer or dedicated server?
those two are completely different things..
if you need to ask such questions, you ain't ready to make multiplayer tbh
also don't crosspost @tropic sparrow
but i mean, what should maxsize be
the size of the collider?
I have a 3D aset with a dedicated server and another aset with Proton 2 Free. I want speed and a lot of players. Please tell me which aset is best for me to work with.
no. read the docs I sent.
the maximum amount of colliders that can be hit with the overlap
both online multiplayer
o h,
in theory the amount of objects?
i mean cuz, this thing is just for the player
thats a vague ass question.. also #1390346492019212368
if its just for the hitting player put like 5 just in case instead of 1
It's vague because I'm a newbie, but I'm looking for help from people like you.
but, what if needs to hit a lot of different enemies? cuz the player will have a similar logic
btw isn't there another way to make this script go 3D?
there is no way to speed up downloads for your players easily, thats up to their internet and where your server is located also, you can do region based or maybe CDN
its literally the same exact function
works the same way except 3D physics engine / colliders
you asked for optimized suggestions way of the code, i said nonalloc is such a thing
yes 2D also has two versions of those functions that return multiple colliders
as I said if you don't call it every frame for the most part is fine, but its just another optimization area
ok
its more noticeable when you have dozens of objects calling that function . and frequent, creating new array every time has its cost to clean and create every time
but btw, for the case of a lot of enemies, what i should put?
in theory i have 5 enemy classes
how many do you think you will hit at same time ? even an exaggerated 50+ will be cheaper than creating a new one over and over, than one thats that big cause its pre-allocated
makes sense
the function will returns how many have been actually hit.
hits = Physics.Overlap(..., colliders,..
for i ; i < hits
var hit = colliders[i] ```
something like this?
private Collider[] hitResults = new Collider[5];
protected void constantMeleeAttack(float attackRange, Transform meleePos, LayerMask victim, float meleeDamage)
{
if (HasHitValeria) return;
Vector3 macheteRange = new Vector3(attackRange, attackRange, attackRange);
Collider[] hitEnemies = Physics.OverlapBox(meleePos.position, macheteRange / 2, meleePos.rotation, victim);
foreach (Collider hitEnemy in hitEnemies)
{
if (hitEnemy.TryGetComponent(out valeriaController64 enemy))
{
enemy.TakeDamage(meleeDamage);
HasHitValeria = true;
break; // Avoid hitting multiple times in one swing
}
}
}```
also this still works, right?
{
HasHitValeria = false;
}```
everything works the same..
hitResults would go in Physics.OverlapBoxNonAlloc, check docs for signature if you switch it
btw this code is ok then?
and you will need for loop instead of foreach because you need to iterate by index
huh?
idk, my only idea, was to be able to hurt the player if touches it, but if doesnt, then dont hurt it again until is reseted
it was based on this other func
{
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(meleePos.transform.position, MacheteRange, 0f, victim);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out valeriaController64 enemy))
{
enemy.TakeDamage(meleeDamage);
}
}
}```
if it worked before , everything should work the same
ok
Nav, you who know a lot, please tell me your opinion of this asset, could it or not give money when completed and would it be for mobile: https://assetstore.unity.com/packages/templates/systems/advanced-multiplayer-game-template-241288?srsltid=AfmBOoquvd3FzO3VbO7TKd2y65zCksS44EgTf1BP1ogfK0Q-TVH_VeQf&utm_source=chatgpt.com
Making a performant MMO is a very complicated task. Slapping something together with photon as a newbie is going to be questionable at best.
nah i'm no expert mate lol
personally would think a template is a waste of money if you're not very experienced knowing how to modify it to make it work
If you think you're going to make the next GTA MMO with photon, you've got a very long way to go
especially if you're new to networking.
sorry.
yeah seriously, if you want to make something with networking do like tic tac toe or something , build your knowledge up
Every week someone with 1 week of unity experience wants to know how to build GTA 5
Quick question for more expericened unity devs. How long do you think it will take to create a simple pokemon like battle engine (nothing really fancy just basic combat)
Bro, that template doesn't have Proton, the store would only incorporate real conoras, that's easy with cha GTP, the 3D models are made for you on a page with animation yet, I don't understand where the complication lies.
Sorry, I'm not trying to ridicule you. But you're talking about wanting to build an online GTA-style MMO with chatgpt
but this is ridiculous
integrating proton or whatever framework is the hard part
you will have "good assets" with busted ass networking
At the very least, you should know how clientside prediction works like the back of your hand, if you want to pull this off
implementing gameplay code on top of an existing multiplayer engine is not easy
especially when it ties into rollback
That's right, I agree with you, I mean, it doesn't work with your current online system, right? It's not Proton, well, it has a dedicated server, something like that.
being dedicated or not is irrelevant to the framework, ie Proton
dedicated just means you host it on a computer somewhere else other than your / users pc
It looks like this asset comes with a custom multiplayer solution
yeah merging something like proton into a custom built system is going to be even more diffcult, you're better off starting simpler and build your knowledge up, you might not even want template by that time
It looks like an asset flip black box asset (eg: snake oil)
no, especially if you're looking for an asset to be turn key solution
everytime something goes wrong you have contact the developer of the asset
if you try to put another networking framework they will probably hesitate to help even more
It says it uses Mirror
hmm better than custom I suppose
Bro, I'll tell you what I have: a 2D shooter game with 7 characters, each with different weapons, a points system or points table for deaths and functional kills, a store to exchange characters for game points, everything already implemented, Proton 2 Free also implemented, a cap purchase system, maps ready, I only need rankings and to change Proton Premium, what do you think?
Mirror is somewhat documented okay at least
mirror is mainly client authoritative afaik
hack fest
not suitable for building a GTA clone
yeah I recall that was its main selling point it was more friendly for client side prediction
or was that Fishnet
fishnet is more server auth
but its still a complete mess
even when you have a network engine suitable for rollback, its still very difficult to write proper rollback gameplay code on top of it unless you know rollback like the back of your hand
what do you think
(its photon, not proton)
Nobody can answer your question unless you know what you want.
Do you want client authoritative or server authoritative? Do you know the difference?
Sounds to me like you haven't even scratched the surface of research for this project
Proton VPN? 😅
I want and I have a functional multiplayer server implemented, I want to earn money by purchasing characters within the game
You're ignoring my questions
You can slap something together with mirror fast using client authoritative networking, but it will be vulnerable and people can hack away to their hearts desire
Or you can build something secure with server authoritative networking (Which requires a significant amount of networking knowledge usually)
All of the unity netcode engines do something different. It depends on your knowledge level, how much money you have to burn, how much time you have to burn. Etc.
If you were me, what would you do? And it seems to me that they are making fun of Proton. The premium is not worth it, perhaps at $95 a year.
christ
btw just saying, wich code's better, the one im replying or this one?
protected void ConstantMeleeAttack(float attackRange, Transform meleePos, LayerMask victim, float meleeDamage)
{
if (HasHitValeria) return;
Vector3 boxSize = new Vector3(attackRange, attackRange, attackRange);
Collider[] hitEnemies = Physics.OverlapBox(meleePos.position, boxSize * 0.5f, Quaternion.identity, victim);
foreach (Collider hitEnemy in hitEnemies)
{
if (hitEnemy.TryGetComponent(out valeriaController64 enemy))
{
enemy.TakeDamage(meleeDamage);
HasHitValeria = true;
break; // Stop after first hit
}
}
}```
i dont know, what if didnt fully worke on 2D? i didnt done a lot of tests
btw, if you put cs at the start of your codeblocks it makes them a little easier for us to read
like this?
yup 
If you want, you can make an interface like IDamageable, and slap that on any gameobject script
and you'll have a very universal damage system
let me know if you need an example
If I had everything I already have in my 2D shoter project with an integrated controller system, what multiplier system would you put: Proton Premium or Mirror or something else?
Its photon. not Proton.
Photon and Mirror are completely separate in terms of their capabilities
do you want server authoritative or client authoritative networking?
If you can't answer this, then you need to do more research on what it means.
wat
one sec
no i mean
what i want is that if the victims, wich are some npcs that share the same code with same func in common, are damaged once, can't be damaged again until the the reset func is set
thats all
nothing else
yes
authorized customer wish in my game
that is probably fine @acoustic belfry
but i mean, wich code is better
consider starting with the basics on !learn before jumping into multiplayer
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If you want a secure server, then you need to run the simulation on the server
game networking gets extremely complicated
and I think you need to do more research rather than trying to slap something together within a week
Photon does this.
if you don't know what you're doing, then you can fully expect someone to hack your server and generate infinite money.
photon is then appropriate
If you know what you're doing
then sure
anyone can generate packets and send it to a server saying "I completed a quest. Give me 5000 tokens"
running photon doesn't prevent this, unless you write your code securely
In conclusion, Photon is more hackable, right?
no
you're ignoring everything I'm telling you
or maybe theres a language barrier here I dont know
exolicame for brutes
pretty sure they're just trolling
And what is the best template for you to start and make money quickly in 2D multiplier?
Please pass me the Roblox Mobile template.
If you're just going to spam nonsense here, you will be kicked from this server.
Whats fine?
Sorry i get confused easily ;-;
If it works, its fine.
You're hardcoding your damage system which I wouldn't consider "fine", but if it fits your needs and works, then it doesnt matter
I was looking at this one, fyi
But i meant, wich one of the two are better?
Idk, i just wonder wich one of em both works better
Completely subjective question
which I dont think I can answer
they look completely identical to me
Hi, I have super simple tile generator but I can't see anything (verts: 3 in the preview). No errors.
All tiles are added to the scene with proper transform, material and mesh.
Camera can move (tested for z=0 and z=-100).
Can you help?
public class Tile
{
public const int size = 32;
public Tile(Vector2 position, Material material)
{
var gameObject = new GameObject($"Tile_{position.x}_{position.y}");
MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>();
MeshFilter filter = gameObject.AddComponent<MeshFilter>();
Mesh mesh = new Mesh();
mesh.vertices = new Vector3[]
{
new Vector3(0, 0, 0),
new Vector3(0, size, 0),
new Vector3(size, size, 0),
new Vector3(size, 0, 0),
};
mesh.uv = new Vector2[]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(0, 1),
new Vector2(1, 1)
};
mesh.triangles = new int[] { 0, 2, 1, 2, 3, 0 };
mesh.RecalculateNormals();
filter.mesh = mesh;
renderer.material = material;
gameObject.transform.position = new Vector3(position.x * size, position.y * size, 0);
}
}
public class TestGoScript : MonoBehaviour
{
void Start()
{
Dictionary<Vector2, Tile> tiles = new();
Material ground = Resources.Load<Material>("Materials/Ground");
ground.color = Color.red;
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 5; y++) {
var tile = new Tile(new Vector2(x, y), ground);
tiles.Add(new Vector2(x,y), tile);
}
}
}
}
I mean, wich one seems more simplier and optimizer or easier to read?
again, they both look the same. you're obsessing way too much over it
neither of them are "simple" because you're hardcoding your damage system rather than using interfaces
Oh, ok, well thanks
you dont need to worry about optimization at this level
your processor spins billions of times every second
Well, thanks :3
What do you mean by you cannot see anything?
literally this:
what are you expecting to see? Are there any objects in view of the camera?
as you can see from the code, 50 squares with the same material (or red if not found)
You can click the scene tab while the application is running and see where the objects-tiles are and the camera direction etc
the code looks like it's probably making the triangles backwards
they need to be clockwise, not counterclockwise
check scene view and rotate the camera
I've spent literally 30 minutes of conversation about indexes with AI, couldn't understand it. I swear it was easier for me to learn in low level API 😄
what's the proper index then?
the only way to make progress with procedural mesh generation is to get a notebook and a pen and DRAW the vertices, labeled
you want to be forming clockwise triangles
unity is working on counter-clockwise indexes for face meshes
afaik clockwise indexes are used for culling as per befault shader settings in unity
so what is wrong with my index then?
Your vertices are like this:
1 2
0 3
0, 2, 1 is a counterclockwise triangle
you need clockwise triangles to be visible with the default material
you need to visualize things on paper to work with procedural meshes
I'm a beginner to coding. Can someone give me advice for the best way to start?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thank you!
it didn't help
I changed the code based on unity doc:
mesh.vertices = new Vector3[]
{
new Vector3(0, 0, 0),
new Vector3(size, 0, 0),
new Vector3(0, size, 0),
new Vector3(size, size, 0),
};
mesh.uv = new Vector2[]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(0, 1),
new Vector2(1, 1),
};
mesh.triangles = new int[] { 0, 2, 1, 2, 3, 1 };
mesh.RecalculateNormals();
mesh.RecalculateBounds();
I found that standard shader is just not rendering... when I change to other shaders it stars to render something...
how can I debug this
TLS Allocator ALLOC_TEMP_TLS, underlying allocator ALLOC_TEMP_MAIN has unfreed allocations, size 544?
or is this harmless
seems like it's only an error that appears in the editor
when i delete the main camera the error stops appearing
sorry for bother, but in theory, this is what you wanted me to do?
protected void constantMeleeAttack(float attackRange, Transform meleePos, LayerMask victim, float meleeDamage)
{
if (HasHitValeria) return;
Vector3 meleeRange = new Vector3(attackRange, attackRange, attackRange);
Collider[] hitValeria = new Collider[5];
int hitsCount = Physics.OverlapBoxNonAlloc(meleePos.position, meleeRange, hitValeria, Quaternion.identity, victim);
for (int i = 0; i < hitsCount; i++)
{
if (hitValeria[i].TryGetComponent<valeriaController64>(out var enemy))
{
enemy.TakeDamage(meleeDamage);
HasHitValeria = true;
}
}
}```
You should declare the array in the class scope so it's allocated once in the lifetime of this object
oh ok, thanks
you mean the variables area in top of the class, right?
just to be sure
Anywhere in a class outside of a method
ok
So yes, the area where you might declare variables, which is typically at the top of a class
i just realized to this moment, i can make variables anywhere that isn't a method
cool
cool, thanks :3
public class CameraMovement : MonoBehaviour
{
public float XRotation;
public float YRotation;
public Transform player;
public float mouseSensitivity = 3f;
public float BopAmount;
public Vector3 OrigPos;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
PlayerInput();
}
void PlayerInput()
{
XRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
YRotation += Input.GetAxis("Mouse X") * mouseSensitivity;
XRotation = Mathf.Clamp(XRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(XRotation, YRotation, 0);
player.transform.rotation = Quaternion.Euler(0, YRotation, 0);
}
}
``` for some reason my player isnt rotating
Log the value of x and y rotation
Debug.Log($"Player input x: {xRotation}, y: {yRotation} and sensitivity: {mouseSensitivity}", this);```
the input is working fine
my camera is rotating smoothly, but my player doesnt rotate even though its rotation is updating
Can you show the data from the log above?
i ran into a bug i cant even fathom, when i change my X, Z position and any sort of rotation, my Y axis changes positive, this occured after i added a rigidbody to my player, please tell me if you need anything to help me diagnose this issue
How are you determining this? Inspector or through code when changing the values? Can you show any logs if through the console. Any images, if from debugging or the inspector.
i can see the Y axis changes via inspector and gamespace there is no errors and i dont know how to debug the rigidbody
How are you rotating the object? Show the necessary code.
im moving it by mouse
all of the input is basic fps movement controls
W,A,S,D and mouse camera movement
Assuming this is a coding issue, if you don't provide any code I won't be able to determine why the value becomes negative.
sorry i was having complications
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 10;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update() {
// Movement Controls
var dir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
transform.Translate(dir * moveSpeed *Time.deltaTime);
}
}
public class FirstPersonCameraController : MonoBehaviour
{
public Transform Player;
public float mouseSensitivity = 2f;
float cameraVerticalRotation = 0f;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float inputX = Input.GetAxis("Mouse X")*mouseSensitivity;
float inputY = Input.GetAxis("Mouse Y")*mouseSensitivity;
cameraVerticalRotation -= inputY;
cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
transform.localEulerAngles = Vector3.right * cameraVerticalRotation;
Player.Rotate(Vector3.up * inputX);
}
}
There isn't any random bug that I'm aware of that sets the y component of rotation to negative when etc
yeah i apologise it was saying i couldnt send the message
Is there any other issue than the value in the inspector? Does it still work otherwise correctly?
no so i just get launched up
i can walk, look perfectly it just also adds to the Y-Axis
None of that code uses the rigidbody to move or rotate so if you want to use rigidbody physics you have to switch to using the rigidbody to move
oh shoot i just realised
thank you ill change it and see if that fixes it
LMAO so i changed the movement and it puts me back down but when i look i get sent up
i should be able to fix that too thank you nitku
If you're modifying an object's Transform component, you may want to sync the Transform component with the physics simulation after you're done with the modifications.
thank you
If you don't feel that you want to batch the operations, you can probably set this auto sync property to true
https://docs.unity3d.com/ScriptReference/Physics-autoSyncTransforms.html
but you should be aware that any and all changes to a Transform component will sync the component
That's not a solution to this problem
Yeah, we aren't aware of the movement system. They've only mentioned that when moving, they're down (on the ground, perhaps) but when immediately looking, they get sent back up.. unless they're referring to simply their forward movement direction being where they're looking at instead of horizontal to the floor etc...
I'm guessing rotating the player moves the collider inside the ground and the physics engine then ejects the player up to fix the collision. But the physics components already follow the transform position, doing that manually is only needed in very niche situations. And movement/rotation should be driven by the rigidbody instead of transform
How would I go about moving on low poly terrain, still following the mesh but without that bumpy, slow, and getting stuck feeling?
do i just place the script in the object itself or am i missing something else?
I'm confused on how to do outlines on my pixel fonts (16px sized font)
I've been off unity for a while coming from Godot.
In godot I just activate the outline button and tell it the color/pixels I want to go outward (4px)
But in unity, the "out"line goes inward, making it look horrendous. The outline seems to give a gray blur to the inner white too
here's my expectations (which I get done in Godot) and what I get in unity attached
I'm probably doing the font settings wrong but I can't figure out which ones I should go for and not have them super blurry (increasing the padding for instance made it unreadably blurry)
currently im trying to make the player look at the point at which the raycast from the screen hits the aimmask (that being a large transparent cylinder that follows the player around) but the if statement never seems to be fulfilled so am i implementing the layer wrong?
RaycastHit hit;
if(Physics.Raycast(ray, out hit, Mathf.Infinity, aimMask))
{
//raycast hit, return position
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
Remove the mask and check if it's actually hitting any collider first off
I would even draw the ray outside of the method to actually see if it's pointing correctly
i figured it out 😐
my interpretation was that it was checking for the mesh renderer and not the collider, so i left the box collider ticked off
lo and behold when i finally turned it on again it worked ffs
anyways many thanks lol i learned how to use debug drawray
is there a smart way to make my projectile shoot the other way when my character turns around without making a new projectile prefab copy that's for shooting left only?
https://paste.mod.gg/skunaxsircfa/0
A tool for sharing your source code with the world!
have the script that creates the fireball set a direction on it. Instantiate() returns the clone. You could multiply the fireballSpeed by -1 to reverse it.
Although it would be better to have a separate int variable for the direction.
it's now acting like a boomerange what did i do wrong😭
using System.Collections;
using UnityEngine;
public class Fireball_Behaviour : MonoBehaviour
{
public float fireballSpeed = 10;
private float direction = 1f;
bool isFacingRight = true;
public void SetDirection(float dir)
{
direction = dir;
transform.localScale = new Vector3(direction * Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
Debug.Log($"Fireball direction set to: {direction}");
}
private void Update()
{
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
isFacingRight = true;
}
else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
isFacingRight = false;
}
if (isFacingRight)
{
direction = 1f;
}
else
{
direction = -1f;
}
transform.position += Vector3.right * direction * fireballSpeed * Time.deltaTime;
}
//removed despawn logic related stuff so it wont clog the chat that much
}
}
}
you are checking on your fireball if the left or right arrow is pressed. I assume you want that logic to be on your player instead. The fireball only needs to know the direction of the player when it is spawned.
I would also suggest to let the player set the direction as Vector3. Right now you have a hard coded "Vector3.right" in your fireball script. By having the player pass a vector you can have it easier to add things like shooting up or at 45° later on.
Do someone know that why my character in rotating in pressed button's direction instead of walking in that direction?:
try disabling the animator for a moment
also show your Rigidbody inspector - and double check that rotations are constrained
Also remove the PlayerInput component, since you're using the generated C# class - there's no need to have PlayerInput there
What would be the best way of making a ui element accessible in 2 or more scenes? Should i just copy it over to every scene used, or is there some way to keep it?
For context, my game is a visual novel, and i want the save menu to be accesible from both the main menu and the actual game scene, and i was thnking of how to best go about it
Using multiscene loading
hi, i'm adding resolution options to my game so i'm trying to filter by the refreshrate but it seemingly doesn't work
int a = (int)resolutions[i].refreshRateRatio.value;
int b = (int)Screen.currentResolution.refreshRateRatio.value;
if (a != b) return;
``` it always returns true
It's debugging time! Put in Debug.Log($"res: {resolutions[i]}, a: {a}, b: {b}"); before the condition and see what it prints
ok! weird thing it works in editor as Screen.resolutions in editor returns ones with same refresh rate as your own but in build it doesn't!
here's one of the logs in editor res: 640 x 480 @ 144.003164815087Hz, a: 144, b: 144
So, a != b should yield false
i know right it's confusing that in the editor it works but not in the build?
You'll have to show the full context. There's no indication here that that particular statement would cause the issue.
Having return inside a loop will stop the loop from continuing further so if the list of resolutions is in a different order in a build it can certainly cause it behave differently
i thought thats what break does?
break exits the loop and continues from the end of it. return ends the entire function, which also would mean ending the loop
If the loop is the last thing in the function, the two are identical
(what did you think return does?)
i thought it meant that it would stop that interation of the for loop and continue from the next (i guess this was kinda naive) so should i just replace it with if(a != b)
That's continue
well i tried continue that didn't work.
It's not really possible to tell what you should do without seeing the whole thing
for (int i = 0; i < resolutions.Length; i++)
{
int a = (int)resolutions[i].refreshRateRatio.value;
int b = (int)Screen.currentResolution.refreshRateRatio.value;
if (a != b) continue;
string option = resolutions[i].width + "x" + resolutions[i].height;
options.Add(option);
}
well i tried continue but that did not do what I want
So, what're you trying to do?
i'm trying to filter it so that it's only resolutions with the same refresh rate as ours.
And what options were found?
If you can see the resolution options given and found, you'd be able to verify what went wrong.
For instance, if you're getting no options.. you'll want to check if there were no resolutions, your screen resolution and why none had matched
ok so the continue worked! but now that index is out of sync.
index out of sync ?
sorry i didn't give much context.
Resolution resolution = resolutions[index];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode);
this is how i'm setting my resolution but because the array has all the elements while the dropdown only has a few they don't match.
you could simplify the flow here
for (int i = 0; i < resolutions.Length; i++)
{
int a = (int)resolutions[i].refreshRateRatio.value;
int b = (int)Screen.currentResolution.refreshRateRatio.value;
- if (a != b) continue;
+ if (a == b) {
string option = resolutions[i].width + "x" + resolutions[i].height;
options.Add(option);
+ }
}
would probably be less confusing/easier to work with if you haven't gotten ahold of continue/break/return yet
make a new array / add them to a seperate list
then you can also use that for Options in dropdown
brillant!
Where does index come from? It should be from the filtered list instead of the original
Cache the indices as well?cs options.Add(option); optionIndex.Add(i);``````cs resolutions[optionIndex[index]]
Hey guys anyone know any AI movement systems that can copy animal behaviour cause I’m making a nature game
use navmesh
is there anyway to have a folder access somewhere outside of the project?
ofc
thats why things System.IO exists, or even Application.persistentDataPath
no not like getting stuff for save files. i mean that let's say i have a sfx folder on my desktop and i want a folder in my unity project to access that.
a folder in unity ? like in the game ? or you mean in the editor
editor.
Your assets need to be in your project
ya just put them in the project, whats the big deal
ok.
also how can i only have one function execute in edit mode in update?
Why
because i have telephone poles that in update will auto rotate themselfs but only need to be executed in edit mode
If the monobehavior has the [ExecuteAlways] attribute then Update() will be called outside of play mode. You can then do something to restrict a call to edit mode only:
#if UNITY_EDITOR
if(!Application.isPlaying) DoEditorThing();
#endif
thanks so much!
Make sure to set your object as dirty manually if its modified because changes made this way will not do this and may mean they are not saved. If the scene is marked dirty by something else it will work.
You can use SetDirty() or the Undo class to record the change as an undoable operation.
https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
make sure that editor only code uses conditional compliation like my example to avoid errors when attempting to build
You’d also have to wrap the using for this
Yes or cheat and do UnityEditor.EditorUtility.SetDirty()
doesn't [ExecuteAlways] make the whole script run in the editor? i only want one thing to run in the editor.
Yes and you cannot get around this
You will have to add things to return early in Start/Awake ect when not in play mode
why does it need to be in Update? can it not just be a context menu item to trigger it manually?
Can also just realistically be in update forever if it’s just transform stuff tbh
You can do better once you get more comfortable
are there any disadvantages in using a signal to trigger a method in another component script over accessing the method directly
by "using a signal" are you referring to an event? or do you mean something else?
oh yeah unity event, sorry
godot brain moment
Thx, it worked after checking constraint rotations
There's a small amount of overhead if using an event to invoke a method versus just calling the method, but it's very slight and shouldn't be worried about. If the workflow of using an event makes the code cleaner (less two-way coupling, better encapsulation, expandability, etc.) it's worth it
then no, there are not really any disadvantages. really only advantages as it would mean your objects don't necessarily need references to each other as data can be passed through the event
🤓 to be fair unity also has "signals" with Timeline
alright thanks
unity event subscriptions done in the inspector are slower vs code subs
Why? inspector way needs to use reflection to locate the function to call
yeah but it's a difference that's not really even worth worrying about too much because it's a one time cost at the time the object is instantiated
Yea probably fine but a real event will be best and probably gets more optimisations (if any exist)
If we can trust mono 😐
i know i keep asking questions but for some reason gamepad input doesn't work in build.
see this message for what to include when asking for help: #🌱┃start-here message
i have tried Googling it and debugging in builds i very difficult.
okay so have you considered providing any useful information at all?
what kind of information do you want?
i checked the game is 64x as that can sometimes cause it as well as checking any input system settings i have also updated the asset but still no luck.
the game is 64x
i have also updated the asset
what asset
nobody here can read your mind, provide useful information
and have you bothered checking the logs for the built game? there may be errors you don't know about
i don't even know anymore than that, also by asset i mean Input System
buddy we aren't sitting over your shoulder
we don't even know what you're building for
What is that white board? How should I remove that? I don't know how is that get added:
click it and see what comes up
also not a code question
Ok, but that is not clickable
i fixed it! it was steam input.
real
start disabling gameobjects then and see which one turns it off then inspect the object
Ok
Hi, for a weird reason my laser doesn't appear, why?
{
Debug.Log("ShootedRifle is even shooting");
rifle_amount--;
// Get a ray from the camera in the direction of the mouse cursor
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, demons))
{
Debug.Log("ShootedRifle has Shooted");
Debug.Log("ShootedRifle hit 3D: " + hit.collider.name);
EnemyBase enemy = hit.transform.GetComponent<EnemyBase>();
if (enemy != null)
{
Debug.Log("ShootedRifle's enemy isn't null");
enemy.TakeDamage(5, 1, 3, 3, transform);
}
// Draw tracer from weapon to hit point
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, hit.point);
}
else
{
// If nothing is hit, draw tracer forward
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + ray.direction * 100);
}
}
Anyone got any ideas on how I could do this? This is using TextMeshPro
BulletsLeft is a float type, text expects a string.
You can convert it with BulletsLeft.ToString();
Why is BulletsLeft a float? Can you shoot partial bullets?
$"{BulletsLeft}";
BulletsLeft + "" 
i have an object that i want to make it move like a human spine but its really hard to animate it manually and i just find out about rigging is it the answer to my problem?
yes
okay thxx for the confirmation 🙏
sorry, is just now im wondering if the issue is of coding or of the line itself
now im realizing, the line appears, but small and inside of the player
probably the rotation of the line renderer that has to be fixed too
how do i fix that?
pause the game, rotate the transform , test alignment and use world space on the line renderer
until you find out what fits
rotate the transform?
you can use a parent gameobject, there are many ways
for example?
i just wanted to give you a hint what the problem might be and in most cases it is the rotation of the line renderer
oh
you will have to find out
well, thx
Ew string concatenation
🤔 what's wrong with it 🤣
"nothing" + " " + "wrong" + " " + "with" + " " + "it"
uuh any idea on how to fix this problem, some object are facing the right way, others don't and I can't change their transform properties in project files
nothing just a whole lot easier to use string interpolation for anything that needs me adding values to a string. Im not left spending 5 minutes fumbling my keyboard typing with the quotes and +
Hi. I would like to know what's the proper way to organize large-scale UI. Pause menu, Game Over menu, Main menu, Inventory, etc.
Is it adviseable to have multiple canvases, for example? Tips like these would help figure out my problem.
Excuse me if this is not the most proper channel.
Thanks, that channel didn't appear on my sidebar.
hey insanely simple question, my model isnt facing transform.forward whats an easy to fix for this?
blender or do the parenting trick
let me reword my bad, i just noticed the empty object i
its under is the one with the wrong transform
do i just make a new empty object?
moving the model alone seems to move the empty's transform too..
you are in Center mode in scene view
you need to switch to Pivot mode to see the actual object position
You can toggle this with the Z key
no right here the blue line isnt the same way as the model's blue line this is the empty;s transform
running the code makes it act like this is its forward
so it chases me with its side
And I'm telling you that the reason the "model seems to move the empty's transform too" is because of a scene view setting
I'm not disagreeing that your model is oriented improperly
Make sure your tool handle position is set to Pivot and the rotation is set to Local in order to properly be able to work on fixing it
Huh.. the model;s pivot is like off to the side..?
Go fix it in blender
ok
isnt this correct?
Oh wait is that point thing the pivot? im a bit new to this
can you show the object in Unity without cropping the screenshot at all
show the full unity window
this is the parent object
select the actual object with the MeshRenderer
Hello actually i have this to make move my player Vector2 axe = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")); rb.linearVelocity = new Vector3(axe.y * speed, rb.linearVelocity.y, axe.x * speed); but if i rotate the player he dont go forward he keep the axis of the world does something like rb.linearVelocity.local exist to make it go in the way i want ?
transform the input vector by your object's rotation
do u want me to send each's pivot...?
e.g.:
Vector3 input = new Vector2(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 velocity = rb.rotation * input * speed;
velocity.y = rb.linearVelocity.y;
rb.linearVelocity = velocity;```
are any of them wrong?
are any of the rotations wrong?
ok ty 🙂
yeah all of them have the blue line facing up
then you need to fix them
Hey I’m making a bullet that can work for both the enemy’s and players but I don’t know how to make a targeted layer mask that only detects
Google: how to properly export from blender to unity
ohh shit wait
Did you accidentally the end of your sentence there?
That only detects the targeted layer
this is supposedly the "front" view is that the wrong thing?
So what's the goal exactly?
just rotate n ez pz?
I want a bullet to have a targeted layer(already set in another script)
That can detect when an object has a layer
Wait….: should I be doing this with tags
no i mean
something like:
"bullets fired by the player should only be able to hit enemies and bullets fired by enemies should only be able to hit players"
something like that
certainly not tags
So is this what you want or..? something else?
Yeah I want that
you can set up the layer collisions in the layer collision matrix (in physics settings), then when you spawn the bullet just set it to the layer you want.
you can make a field in the script that shoots them like public int bulletLayer; then set that layer on the bullet when you spawn it
ok i fixed it !!! the reasons for it blending into the floor was cuz i had the model all wrong and for it to be facing me with its side was also with its model, i just fixed it by rotating it and moving it slightly up 👍 ‼️
yeah now that i think abt it testing before giving it all those details was important 😭
can anyone recommend me some tutorials on 2d isometric games with height AND characters?
I've followed tutorials on just making the isometric levels and got to a good point where i can create the isometric level but actually putting a character with a sprite on it almost immediately starts giving me trouble (feet clipping into the floor, not being hidden correctly behind walls, etc etc)
most of the tuts i see seem to only cover the level creation though...
Learn how to order your player sprites to be able to walk behind objects. Understand how unity sprite layering, order in layer and the sprite sort points work.
In this video we go over how sprite layering is prioritized, what a sorting layer is. How to set the sprite order in a layer and the sprite sort point so that you can get your player and...
just grabbed the first one i saw.. but use keywords like "[unity] isometric map sorting order" and you'll find some stuff thats relevant
thats the way most tutorials work.. most of them are going to be covering a specific topic.. you gotta go thru ur game and figure out what types of issues you're gonna have and then learn each subject and adapt them for ur own use-cases
or like me as a beginner just stumbling upon things i didn't know or realize i had to do..
its more about figuring out what the thing im having trouble with is called (or the best way to phrase it) and then finding relevant sources for me
asking around is surely a good way to do that tho.. (figuring out what keywords i need to use)
thats why i came to ask, because i know this idea isnt a unique one yet every tutorial i can find doesnt cover what i need
they only do tilemap sorting (the tiles work fine on their own)
or they do the 2d y-sorting for a topdown (not suitable for my case)
what perspective are u working with?
isometric
with sprites?
yep
making the isometric tilemap works, i have the map, but adding something on top of it that moves dynamically keeps not hiding properly behind walls or getting covered by tiles that it should be on top of
is there a website where I can steal other peoples code?
https://www.youtube.com/watch?v=CTf0WjhfBx8 heres another one.. its basically sorting order depending on which plane ur on..
the positions are what really matters.. ur either in front of something (closer on a certain axis) or ur behind something (farther on a certain axis)
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=CTf0WjhfBx8
This is a quick tip for sorting sprites based on a Front Top Down perspective like in Pokemon Red and Blue.
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials https://www.yo...
its still going to be sorting order.. and distances thats whats relevant
same applies to a 2.5 game wehre ur using a 3d space and 2d sprites on top.. (the player or object still relies on being farther or closer than that object (just comparisons).. based on the players feet/ a trees base (trunk) etc
github, stackoverflow, etc
mhmm
player is on the same y axis, but on the left they should be rendered behind the wall, on the right they should be rendered in front of it
ohh thats true i didnt think of that
so in that case u'd have to compare BOTH axis's
if its behind pivot AND its left of pivot = behind
and then the negative of that = in front
or a combination of certain things
but yea i think the logic behind it is still the same.. but how the system is built could vary
well, thats not the end of it either since this screenshot also doesnt exactly represent my scenario (this video isnt using a tilemap, or at least not unity tilemaps)
i usually only work in 3d im a bit out of my realm.. but i can help keep searching for something relevant
thats why im asking, since i feel like this should be a common issue
isometric games are a bit rarer but not unheard of
and if unity has some built in settings or config to support this, id like to make use of it before trying to bash my head at some sort of sorting myself
where would this kind of comparison even go in unity? since im using unity tilemaps
you may find people that know more about it in #🖼️┃2d-tools its not so much as a code question as it is a general concept
tilemaps still ahve a transform and a position
as well as all ur players / pieces
right but youd need to affect tiles individually
regardless, ill go check 2d-tools
thanks for the redirect
Hi, how i can turn this into 3D?
{
Debug.Log("ShootedRifle is even shooting");
rifle_amount--;
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
RaycastHit2D shootedRifle = Physics2D.Raycast(transform.position, shootDirection, Mathf.Infinity, demons);
if (shootedRifle)
{
Debug.Log("ShootedRifle has Shooted");
Debug.Log("ShootedRifle hit 2: " + shootedRifle.collider.name);
EnemyBase enemy = shootedRifle.transform.GetComponent<EnemyBase>();
if (enemy != null)
{
Debug.Log("ShootedRifle's enemy isn't null '");
enemy.TakeDamage(5, 1, 3, 3, transform);
}
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, shootedRifle.point);
}
else
{
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + shootDirection * 100);
}
}```
Well it's already a Raycast2D so it seems like it already is
my bad
i tried to do this, but for a weird reason, the line doesn't appear, is just, inside the player
{
Debug.Log("ShootedRifle is in the func");
rifle_amount--;
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
RaycastHit2D shootedRifle = Physics2D.Raycast(transform.position, shootDirection, Mathf.Infinity, demons);
if (shootedRifle)
{
Debug.Log("ShootedRifle is even shooting");
Debug.Log("ShootedRifle hit 2: " + shootedRifle.collider.name);
EnemyBase enemy = shootedRifle.transform.GetComponent<EnemyBase>();
if (enemy != null)
{
Debug.Log("ShootedRifle's enemy isn't null '");
enemy.TakeDamage(5, 1, 3, 3, transform);
}
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, shootedRifle.point);
}
else
{
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + shootDirection * 100);
}
}```
Did you try logging the positions of the line and see where they are?
huh?
what you mean?
the line is literaly inside the player, is like it lays it down
i can see it cuz i move, and there is
(yes, the line doesnt go until i shot again, i did it that way so i can check where the line is)
no idea what happened
but now works
but with an small issue
why the line looks like this?
I don't know which line you're asking about but it's going to draw between the two positions you give it. If those positions aren't correct, you probably need to change which positions you give it
oops my bad, i meant why is fady
Because the material you've given it looks like that
Do all Undo operations obviate the need to call SetDirty? So like e.g. if I call Undo.RegisterCompleteObjectUndo(obj, "change obj") would I also need to call EditorUtility.SetDirty(obj) afterward?
huh? and how i can select it?
i just create it and was like that
In the line renderer component
doesn't allow me to modify it
Create and assign a new material. This one is a default engine material, so you can't modify it.
You cannot edit the default material. You will need to assign it a material you created so you can actually edit it
Newsoft JSON has this very cool thing called [Default Value] (from System.ComponentModel) and also ShouldSerialize
How could i make so that in a array i could tell the serializer each default value inside it?
for example [0] default is 0, [1] is 1, [2] is 0.5 and until [7] its 0.5..?
it is possible to use ShouldSerialize to not serialize when the array is the default
private static bool AreArraysEqual<T>(T[] a, T[] b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (a.Length != b.Length) return false;
for (int i = 0; i < a.Length; i++)
{
if (!a[i].Equals(b[i])) return false;
}
return true;
}
but this means that once something within the array is changed, the whole array is serialized
so we waste space
Are you expecting the array to usually have mostly default values?
oh no dont tell me i could make it just floats
also yes
what i mean by this is instead of array float i could do float1, float2, float3..
but yeah that would be bad
Instead of directly serializing the array, you could serialize a list of overrides. e.g.:
overrides: {
{ "index": 5 , "value" : .442321 },
{ "index": 7 , "value" : .02345 }
}```
and i could put the default value for each slot inside the dictionary so that the serializer wont serialize it?
or:
overrides: {
{ "5" : .442321},
{ "7" : .02345}
}```

I think best practice anyway is to have a separate DTO and have a pass where you process the DTO to create your runtime structure
so you would basically just start with the default array and iterate over the overrides to replace values in the default array.
it wouldn't be part of serialization
although I'm sure in newtonsoft you could make it part of serialization somehow
it has a ton of features
thats what im trying to figure
yeah i see

